package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB2Config;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db2.PcbCapacityParamService;
import com.sailfish.springbootdemo.service.db2.PcbParentFactoryInfoService;
import com.sailfish.springbootdemo.service.db2.S3UploadFileService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.FileConverterUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.toJSONString;
import static org.apache.commons.lang.StringUtils.isBlank;

@Service
public class PcbCapacityParamServiceImpl implements PcbCapacityParamService {

    @Autowired
    PcbCapacityParamDao pcbCapacityParamDao;
    @Autowired
    PcbCapacityDataDao pcbCapacityDataDao;
    @Autowired
    PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    PcbParentFactoryInfoService pcbParentFactoryInfoService;
    @Autowired
    PcbCapacityParamHistoryDao pcbCapacityParamHistoryDao;
    @Autowired
    PcbCapacityDataHistory2Dao pcbCapacityDataHistory2Dao;
    @Autowired
    PcbCapacityParamVersionDao pcbCapacityParamVersionDao;
    @Autowired
    PcbCapacityDataApproveDao pcbCapacityDataApproveDao;
    @Autowired
    PcbCapacityApproveDetailDao pcbCapacityApproveDetailDao;
    @Autowired
    PcbApproveProcessDao pcbApproveProcessDao;
    @Autowired
    PcbApproveConfigDao pcbApproveConfigDao;
    @Autowired
    OperateService operateService;
    @Autowired
    UserDao userDao;
    @Autowired
    S3UploadFileService s3UploadFileService;

    /*删除参数*/
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result delete(Integer id) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbCapacityDataApprove search = new PcbCapacityDataApprove();
            search.setFactoryId(0);
            PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getSystemStatus();
            if (pcbCapacityDataApprove != null) {
                Result result = checkHasNotApproved();
                //有未审核通过的
                if (result.getCode() == 500) {
                    return result;
                }
                if (pcbCapacityDataApprove.getApproveStatus().equals("已分发")) {
                    String oldData = JSONObject.toJSONString(pcbCapacityDataApprove);
                    PcbCapacityParamVersion newestVersion = pcbCapacityParamVersionDao.getNewest(1);
                    if (newestVersion != null && newestVersion.getVersionYear().equals(String.valueOf(Year.now()))) {
                        String versionNum = newestVersion.getVersionNum();
                        saveOldParamTemplate(newestVersion.getVersionYear(), versionNum);
                    } else {
                        //修改为使用当前年
                        saveOldParamTemplate(String.valueOf(Year.now())/*"2024"*/, "V01");
                    }

                    pcbCapacityDataApprove.setApproveStatus("待分发");
                    pcbCapacityDataApprove.setUpdateTime(new Date());
                    pcbCapacityDataApprove.setUpdateUser(userId);
                    int count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 3, 1, new Date(), oldData, JSONObject.toJSONString(pcbCapacityDataApprove)));
                    }
                }
            }
            // 获取到了节点下的所有数据（包括本节点）
            List<PcbCapacityParam> allByIdLower = pcbCapacityParamDao.getAllByIdLower(id, null);
            List<Integer> ids = allByIdLower.stream().map(item -> item.getPcbCapacityParamId()).collect(Collectors.toList());
            int count = pcbCapacityParamDao.deleteBatch(ids);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力模板", 2, 1, new Date(), JSONObject.toJSONString(allByIdLower), null));
                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    /*更新参数*/
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdate(String data) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getSystemStatus();
            if (pcbCapacityDataApprove != null) {
                if (pcbCapacityDataApprove.getApproveStatus().equals("已分发")) {
                    Result result = checkHasNotApproved();
                    //有未审核通过的
                    if (result.getCode() == 500) {
                        return result;
                    }
                    String oldData = JSONObject.toJSONString(pcbCapacityDataApprove);
                    PcbCapacityParamVersion newestVersion = pcbCapacityParamVersionDao.getNewest(1);
                    if (newestVersion != null && newestVersion.getVersionYear().equals(String.valueOf(Year.now()))) {
                        String versionNum = newestVersion.getVersionNum();
                        saveOldParamTemplate(newestVersion.getVersionYear(), versionNum);
                    } else {
                        saveOldParamTemplate(String.valueOf(Year.now()), "V01");
                    }
                    pcbCapacityDataApprove.setApproveStatus("待分发");
                    pcbCapacityDataApprove.setUpdateTime(new Date());
                    pcbCapacityDataApprove.setUpdateUser(userId);
                    int count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 3, 1, new Date(), oldData, JSONObject.toJSONString(pcbCapacityDataApprove)));
                    }
                }
            }

            JSONObject jsonObject = JSONObject.parseObject(data);
            String mode = jsonObject.getString("mode");
            Integer parentId = jsonObject.getInteger("parentId");
            String pcbCapacityParamName = jsonObject.getString("pcbCapacityParamName");
            String pcbCapacityParamNameEn = jsonObject.getString("pcbCapacityParamNameEn");
            String indexLink = jsonObject.getString("indexLink");
            String pcbCapacityParamKey = jsonObject.getString("pcbCapacityParamKey");
            String pcbCapacityParamKey2 = jsonObject.getString("pcbCapacityParamKey2");
            String pcbCapacityParamKey3 = jsonObject.getString("pcbCapacityParamKey3");
            String pcbCapacityParamKey4 = jsonObject.getString("pcbCapacityParamKey4");
            Integer level = jsonObject.getInteger("level");
            String unit = jsonObject.getString("unit");
            String tip = jsonObject.getString("tip");
            Integer isRequired = jsonObject.getInteger("isRequired");
            Integer paramType = jsonObject.getInteger("paramType");
            String paramOptions = jsonObject.getString("paramOptions");
            Integer ruleType = jsonObject.getInteger("ruleType");
            Integer status = jsonObject.getInteger("status");
            Integer sort = jsonObject.getInteger("sort");
            String remark = jsonObject.getString("remark");
            String pic = jsonObject.getString("remarkPic");
            Integer pcbCapacityParamId = jsonObject.getInteger("pcbCapacityParamId");

            PcbCapacityParam item = new PcbCapacityParam();
            item.setParentId(parentId);
            item.setPcbCapacityParamName(pcbCapacityParamName);
            item.setPcbCapacityParamNameEn(pcbCapacityParamNameEn);
            item.setIndexLink(indexLink);
            item.setPcbCapacityParamKey(pcbCapacityParamKey);
            item.setPcbCapacityParamKey2(pcbCapacityParamKey2);
            item.setPcbCapacityParamKey3(pcbCapacityParamKey3);
            item.setPcbCapacityParamKey4(pcbCapacityParamKey4);
            item.setLevel(level);
            item.setUnit(unit);
            item.setTip(tip);
            item.setIsRequired(isRequired);
            item.setParamType(paramType);
            item.setParamOptions(paramOptions);
            item.setRuleType(ruleType);
            item.setStatus(status);
            item.setSort(sort);
            item.setRemark(remark);
            item.setRemarkPic(pic);

            if (mode.equals("add")) {
                item.setCreateTime(new Date());
                List<PcbCapacityParam> allByLimit = pcbCapacityParamDao.getAllByLimit(item.getParentId(), item.getPcbCapacityParamName(), item.getPcbCapacityParamNameEn(), item.getIndexLink(), null, null, null, item.getLevel(), null, item.getParamType(), null, item.getStatus(), null);
                if (allByLimit.stream().count() > 0) {
                    return ResultUtil.error(500, "重复添加", "", null);
                } else {
                    int count = pcbCapacityParamDao.insert(item);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力模板", 1, 1, new Date(), null, JSONObject.toJSONString(item)));
                        return ResultUtil.success(item);
                    }
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            } else {
                if (pcbCapacityParamId == null) {
                    return ResultUtil.error(500, "参数id为空", "id is null", null);
                }
                if (parentId == null) {
                    return ResultUtil.error(500, "参数parentId为空", "parentId is null", null);
                }
                item.setPcbCapacityParamId(pcbCapacityParamId);
                item.setUpdateTime(new Date());
                List<PcbCapacityData> oldData = pcbCapacityDataDao.getById(item.getPcbCapacityParamId());
                int count = pcbCapacityParamDao.update(item);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力模板", 3, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(item)));
                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    public Result checkHasNotApproved() {
        PcbCapacityDataApprove param = new PcbCapacityDataApprove();
        param.setFlowType(3);
        List<PcbCapacityDataApprove> pcbCapacityDataApproveList2 = pcbCapacityDataApproveDao.getByLimit(param);
        for (int i = 0; i < pcbCapacityDataApproveList2.size(); i++) {
            if (!pcbCapacityDataApproveList2.get(i).getApproveStatus().equals("已发布")) {
                return ResultUtil.error(500, "PCB工艺能力调查有未审批完成的记录,不可以修改参数模板", "Operate Fail", null);
            }
        }
        PcbCapacityDataApprove param2 = new PcbCapacityDataApprove();
        param2.setFlowType(5);
        List<PcbCapacityDataApprove> pcbCapacityDataApproveList3 = pcbCapacityDataApproveDao.getByLimit(param2);
        for (int i = 0; i < pcbCapacityDataApproveList3.size(); i++) {
            if (!pcbCapacityDataApproveList3.get(i).getApproveStatus().equals("已发布")) {
                return ResultUtil.error(500, "PCB工艺能力修改有未审批完成的记录,不可以修改参数模板", "Operate Fail", null);
            }
        }
        return ResultUtil.success(null);
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result updateRequire(Integer isRequire) {
        try {
            if (isRequire == null) {
                return ResultUtil.error(500, "参数isRequire为空", "param isRequire is null", null);
            }
            if (isRequire != 1 && isRequire != 2) {
                return ResultUtil.error(500, "参数isRequire不正确", "param isRequire is error", null);
            }
            Integer count = pcbCapacityParamDao.updateRequire(isRequire);
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /*获取参数列表 */
    @Override
    public Result getParamList(Integer id1, Integer id2, Integer id3, Integer level, String searchK, String searchV) {
        try {
            List<PcbCapacityParam> paramList0;
            if (id1 == null) {
                String search = null;
                if (!StringUtils.isBlank(searchK) && searchK.equals("type") && !StringUtils.isBlank(searchV)) {
                    search = searchV;
                }
                paramList0 = pcbCapacityParamDao.getParamList(null, 0, search, null, 1);
            } else {
                paramList0 = new ArrayList<>();
                paramList0.add(pcbCapacityParamDao.getById(id1));
            }
            for (int i = 0; i < paramList0.size(); i++) {
                PcbCapacityParam pcbCapacityParam0 = paramList0.get(i);
                final String url = pcbCapacityParam0.getRemarkPic();
                if (!StringUtils.isBlank(url)) {
                    String base64Image = s3UploadFileService.getImageBase64FromUrl(url);
                    pcbCapacityParam0.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                }
                String indexLink1 = pcbCapacityParam0.getPcbCapacityParamId() + "-";
                List<PcbCapacityParam> paramList1;
                if (id2 == null) {
                    String search = null;
                    if (!StringUtils.isBlank(searchK) && searchK.equals("category") && !StringUtils.isBlank(searchV)) {
                        search = searchV;
                    }
                    paramList1 = pcbCapacityParamDao.getParamList(indexLink1, 1, search, null, null);
                } else {
                    paramList1 = new ArrayList<>();
                    paramList1.add(pcbCapacityParamDao.getById(id2));
                }

                for (int j = 0; j < paramList1.size(); j++) {
                    PcbCapacityParam pcbCapacityParam1 = paramList1.get(j);
                    final String url1 = pcbCapacityParam1.getRemarkPic();
                    if (!StringUtils.isBlank(url1)) {
                        String base64Image = s3UploadFileService.getImageBase64FromUrl(url1);
                        pcbCapacityParam1.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                    }
                    String indexLink2 = indexLink1 + pcbCapacityParam1.getPcbCapacityParamId() + "-";
                    List<PcbCapacityParam> paramList2;
                    if (id3 == null) {
                        String search = null;
                        if (!StringUtils.isBlank(searchK) && searchK.equals("param1") && !StringUtils.isBlank(searchV)) {
                            search = searchV;
                        }
                        paramList2 = pcbCapacityParamDao.getParamList(indexLink2, 2, search, null, null);
                    } else {
                        paramList2 = new ArrayList<>();
                        paramList2.add(pcbCapacityParamDao.getById(id3));
                    }
                    for (int k = 0; k < paramList2.size(); k++) {
                        PcbCapacityParam pcbCapacityParam2 = paramList2.get(k);
                        final String url2 = pcbCapacityParam2.getRemarkPic();
                        if (!StringUtils.isBlank(url2)) {
                            String base64Image = s3UploadFileService.getImageBase64FromUrl(url2);
                            pcbCapacityParam2.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                        }
                        String indexLink3 = indexLink2 + pcbCapacityParam2.getPcbCapacityParamId() + "-";
                        String search = null;
                        String tip = null;
                        if (!StringUtils.isBlank(searchK) && searchK.equals("pcbCapacityParamName") && !StringUtils.isBlank(searchV)) {
                            search = searchV;
                        }
                        if (!StringUtils.isBlank(searchK) && searchK.equals("tip") && !StringUtils.isBlank(searchV)) {
                            tip = searchV;
                        }
                        final List<PcbCapacityParam> paramList3 = pcbCapacityParamDao.getParamList(indexLink3, 3, search, tip, null);
                        for (int a = 0; a < paramList3.size(); a++) {
                            final String url3 = paramList3.get(a).getRemarkPic();
                            if (!StringUtils.isBlank(url3)) {
                                String base64Image = s3UploadFileService.getImageBase64FromUrl(url3);
                                paramList3.get(a).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                            }
                        }
                        pcbCapacityParam2.setChildren(paramList3);
                    }
                    pcbCapacityParam1.setChildren(paramList2);
                }
                pcbCapacityParam0.setChildren(paramList1);
            }

            return ResultUtil.success(paramList0);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public Result getParamListHistory(Integer id1, Integer id2, Integer id3, Integer level, String searchK, String searchV, String version) {
        try {
            List<PcbCapacityParamHistory> paramList0;
            if (id1 == null) {
                String search = null;
                if (!StringUtils.isBlank(searchK) && searchK.equals("type") && !StringUtils.isBlank(searchV)) {
                    search = searchV;
                }
                paramList0 = pcbCapacityParamHistoryDao.getParamList(null, 0, search, version);
            } else {
                paramList0 = new ArrayList<>();
                paramList0.add(pcbCapacityParamHistoryDao.getById(id1, version));
            }
            for (int i = 0; i < paramList0.size(); i++) {
                PcbCapacityParamHistory pcbCapacityParam0 = paramList0.get(i);
                final String url = pcbCapacityParam0.getRemarkPic();
                if (!StringUtils.isBlank(url)) {
                    String base64Image = s3UploadFileService.getImageBase64FromUrl(url);
                    pcbCapacityParam0.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                }
                String indexLink1 = pcbCapacityParam0.getPcbCapacityParamId() + "-";
                List<PcbCapacityParamHistory> paramList1;
                if (id2 == null) {
                    String search = null;
                    if (!StringUtils.isBlank(searchK) && searchK.equals("category") && !StringUtils.isBlank(searchV)) {
                        search = searchV;
                    }
                    paramList1 = pcbCapacityParamHistoryDao.getParamList(indexLink1, 1, search, version);
                } else {
                    paramList1 = new ArrayList<>();
                    paramList1.add(pcbCapacityParamHistoryDao.getById(id2, version));
                }

                for (int j = 0; j < paramList1.size(); j++) {
                    PcbCapacityParamHistory pcbCapacityParam1 = paramList1.get(j);
                    final String url1 = pcbCapacityParam1.getRemarkPic();
                    if (!StringUtils.isBlank(url1)) {
                        String base64Image = s3UploadFileService.getImageBase64FromUrl(url1);
                        pcbCapacityParam1.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                    }
                    String indexLink2 = indexLink1 + pcbCapacityParam1.getPcbCapacityParamId() + "-";
                    List<PcbCapacityParamHistory> paramList2;
                    if (id3 == null) {
                        String search = null;
                        if (!StringUtils.isBlank(searchK) && searchK.equals("param1") && !StringUtils.isBlank(searchV)) {
                            search = searchV;
                        }
                        paramList2 = pcbCapacityParamHistoryDao.getParamList(indexLink2, 2, search, version);
                    } else {
                        paramList2 = new ArrayList<>();
                        paramList2.add(pcbCapacityParamHistoryDao.getById(id3, version));
                    }
                    for (int k = 0; k < paramList2.size(); k++) {
                        PcbCapacityParamHistory pcbCapacityParam2 = paramList2.get(k);
                        final String url2 = pcbCapacityParam2.getRemarkPic();
                        if (!StringUtils.isBlank(url2)) {
                            String base64Image = s3UploadFileService.getImageBase64FromUrl(url2);
                            pcbCapacityParam2.setImageBase64(CommonUtils.base64Prefix() + base64Image);
                        }
                        String indexLink3 = indexLink2 + pcbCapacityParam2.getPcbCapacityParamId() + "-";
                        String search = null;
                        String tip = null;
                        if (!StringUtils.isBlank(searchK) && searchK.equals("pcbCapacityParamName") && !StringUtils.isBlank(searchV)) {
                            search = searchV;
                        }
                        if (!StringUtils.isBlank(searchK) && searchK.equals("tip") && !StringUtils.isBlank(searchV)) {
                            tip = searchV;
                        }
                        final List<PcbCapacityParamHistory> paramList3 = pcbCapacityParamHistoryDao.getParamList(indexLink3, 3, search, version);
                        for (int a = 0; a < paramList3.size(); a++) {
                            final String url3 = paramList3.get(a).getRemarkPic();
                            if (!StringUtils.isBlank(url3)) {
                                String base64Image = s3UploadFileService.getImageBase64FromUrl(url3);
                                paramList3.get(a).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                            }
                        }
                        pcbCapacityParam2.setChildren(paramList3);
                    }
                    pcbCapacityParam1.setChildren(paramList2);
                }
                pcbCapacityParam0.setChildren(paramList1);
            }

            return ResultUtil.success(paramList0);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public List<PcbCapacityParam> getChildrenById(Integer id, String paramName, Integer status) {

        PcbCapacityParam search = new PcbCapacityParam();
        search.setParentId(id);
        search.setStatus(status);
        // 获取类型
        List<PcbCapacityParam> paramList0 = pcbCapacityParamDao.getAllByLimit2(search);
        for (int i = 0; i < paramList0.size(); i++) {
            final String url = paramList0.get(i).getRemarkPic();
            if (!StringUtils.isBlank(url)) {
                String base64Image = s3UploadFileService.getImageBase64FromUrl(url);
                paramList0.get(i).setImageBase64(CommonUtils.base64Prefix() + base64Image);
            }
            PcbCapacityParam search1 = new PcbCapacityParam();
            search1.setParentId(paramList0.get(i).getPcbCapacityParamId());
            search1.setStatus(status);
            //获取类别
            List<PcbCapacityParam> paramList1 = pcbCapacityParamDao.getAllByLimit2(search1);
            for (int j = 0; j < paramList1.size(); j++) {
                final String url1 = paramList1.get(j).getRemarkPic();
                if (!StringUtils.isBlank(url1)) {
                    String base64Image = s3UploadFileService.getImageBase64FromUrl(url1);
                    paramList1.get(j).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                }
                PcbCapacityParam search2 = new PcbCapacityParam();
                search2.setParentId(paramList1.get(j).getPcbCapacityParamId());
                search2.setStatus(status);
                //获取大类
                List<PcbCapacityParam> paramList2 = pcbCapacityParamDao.getAllByLimit2(search2);
                for (int k = 0; k < paramList2.size(); k++) {
                    final String url2 = paramList2.get(k).getRemarkPic();
                    if (!StringUtils.isBlank(url2)) {
                        String base64Image = s3UploadFileService.getImageBase64FromUrl(url2);
                        paramList2.get(k).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                    }
                    PcbCapacityParam search3 = new PcbCapacityParam();
                    search3.setParentId(paramList2.get(k).getPcbCapacityParamId());
                    search3.setStatus(status);
                    //获取小类
                    List<PcbCapacityParam> paramList3 = pcbCapacityParamDao.getAllByLimit2(search3);
                    for (int a = 0; a < paramList3.size(); a++) {
                        final String url3 = paramList3.get(a).getRemarkPic();
                        if (!StringUtils.isBlank(url3)) {
                            String base64Image = s3UploadFileService.getImageBase64FromUrl(url3);
                            paramList3.get(a).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                        }
                    }
                    paramList2.get(k).setChildren(paramList3);
                }
                paramList1.get(j).setChildren(paramList2);
            }
            paramList0.get(i).setChildren(paramList1);
        }
        return paramList0;

    }

    @Override
    public List<PcbCapacityParamHistory> getChildrenByIdHistory(Integer id, String version) {
        PcbCapacityParamHistory search = new PcbCapacityParamHistory();
        search.setParentId(id);
        search.setVersion(version);
        // 获取类型
        List<PcbCapacityParamHistory> paramList0 = pcbCapacityParamHistoryDao.getAllByLimit2(search);
        for (int i = 0; i < paramList0.size(); i++) {
            PcbCapacityParamHistory search1 = new PcbCapacityParamHistory();
            search1.setParentId(paramList0.get(i).getPcbCapacityParamId());
            search1.setVersion(version);
            //获取类别
            List<PcbCapacityParamHistory> paramList1 = pcbCapacityParamHistoryDao.getAllByLimit2(search1);
            for (int j = 0; j < paramList1.size(); j++) {
                PcbCapacityParamHistory search2 = new PcbCapacityParamHistory();
                search2.setParentId(paramList1.get(j).getPcbCapacityParamId());
                search2.setVersion(version);
                //获取大类
                List<PcbCapacityParamHistory> paramList2 = pcbCapacityParamHistoryDao.getAllByLimit2(search2);
                for (int k = 0; k < paramList2.size(); k++) {
                    PcbCapacityParamHistory search3 = new PcbCapacityParamHistory();
                    search3.setParentId(paramList2.get(k).getPcbCapacityParamId());
                    search3.setVersion(version);
                    //获取小类
                    List<PcbCapacityParamHistory> paramList3 = pcbCapacityParamHistoryDao.getAllByLimit2(search3);
                    paramList2.get(k).setChildren(paramList3);
                }
                paramList1.get(j).setChildren(paramList2);
            }
            paramList0.get(i).setChildren(paramList1);
        }
        return paramList0;
    }

    @Override
    public List<PcbCapacityParam> getChildrenWithData(Integer id, Integer pcbCapacityHistoryId, Integer pcbFactoryId, Integer valueType) {
        List<PcbCapacityParam> params = getChildrenById(id, null, 1);
        Map<String, String> map = new HashMap<>();
        if (valueType == 1) {
            List<PcbCapacityData> data1 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 1, null, null, null, null, null, null, null, null);
            List<PcbCapacityData> data2 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 2, null, null, null, null, null, null, null, null);

            for (int i = 0; i < data1.size(); i++) {
                map.put(data1.get(i).getPcbParamKey(), data1.get(i).getPcbParamValue());
            }
            for (int i = 0; i < data2.size(); i++) {
                map.put(data2.get(i).getPcbParamKey(), data2.get(i).getPcbParamValue());
            }
        }
        if (valueType == 3) {
            List<PcbCapacityData> data3 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 3, null, null, null, null, null, null, null, null);
            List<PcbCapacityData> data4 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 4, null, null, null, null, null, null, null, null);

            for (int i = 0; i < data3.size(); i++) {
                map.put(data3.get(i).getPcbParamKey(), data3.get(i).getPcbParamValue());
            }
            for (int i = 0; i < data4.size(); i++) {
                map.put(data4.get(i).getPcbParamKey(), data4.get(i).getPcbParamValue());
            }
        }
        for (int i = 0; i < params.size(); i++) {
            List<PcbCapacityParam> categorys = params.get(i).getChildren();
            if (categorys != null) {
                for (int j = 0; j < categorys.size(); j++) {
                    List<PcbCapacityParam> bigType = categorys.get(j).getChildren();
                    if (bigType != null) {
                        for (int k = 0; k < bigType.size(); k++) {
                            List<PcbCapacityParam> smallType = bigType.get(k).getChildren();
                            if (smallType != null) {
                                for (int m = 0; m < smallType.size(); m++) {
                                    if (!isBlank(smallType.get(m).getPcbCapacityParamKey())) {
                                        String key1 = smallType.get(m).getPcbCapacityParamKey();
                                        String key2 = smallType.get(m).getPcbCapacityParamKey2();
                                        String key3 = smallType.get(m).getPcbCapacityParamKey3();
                                        String key4 = smallType.get(m).getPcbCapacityParamKey4();
                                        if (valueType == 1) {
                                            String value1 = map.get(key1);
                                            String value2 = map.get(key2);
                                            String str_value1 = "";
                                            String str_value2 = "";
                                            if (smallType.get(m).getParamType() == 6)//公差
                                            {
                                                if (!StringUtils.isBlank(value1)) {
                                                    String[] arr = value1.split(",");
                                                    if (arr.length == 1) {
                                                        str_value1 = "±" + arr[0];
                                                    }
                                                    if (arr.length == 2) {
                                                        str_value1 = "+" + arr[0] + ",-" + arr[1];
                                                    }
                                                }
                                                if (!StringUtils.isBlank(value2)) {
                                                    String[] arr2 = value2.split(",");
                                                    if (arr2.length == 1) {
                                                        str_value2 = "±" + arr2[0];
                                                    }
                                                    if (arr2.length == 2) {
                                                        str_value2 = "+" + arr2[0] + ",-" + arr2[1];
                                                    }
                                                }
                                            } else {
                                                str_value1 = map.get(key1);
                                                str_value2 = map.get(key2);
                                            }
                                            if (map.containsKey(key1)) {
                                                smallType.get(m).setPcbCapacityParamValue(str_value1);
                                            }
                                            if (map.containsKey(key2)) {
                                                smallType.get(m).setPcbCapacityParamValue2(str_value2);
                                            }
                                        }
                                        if (valueType == 3) {
                                            String value3 = map.get(key3);
                                            String value4 = map.get(key4);
                                            String str_value3 = "";
                                            String str_value4 = "";
                                            if (smallType.get(m).getParamType() == 6)//公差
                                            {
                                                if (!StringUtils.isBlank(value3)) {
                                                    String[] arr3 = value3.split(",");
                                                    if (arr3.length == 1) {
                                                        str_value3 = "±" + arr3[0];
                                                    }
                                                    if (arr3.length == 2) {
                                                        str_value3 = "+" + arr3[0] + ",-" + arr3[1];
                                                    }
                                                }
                                                if (!StringUtils.isBlank(value4)) {
                                                    String[] arr4 = value4.split(",");
                                                    if (arr4.length == 1) {
                                                        str_value4 = "±" + arr4[0];
                                                    }
                                                    if (arr4.length == 2) {
                                                        str_value3 = "+" + arr4[0] + ",-" + arr4[1];
                                                    }
                                                }
                                            } else {
                                                str_value3 = map.get(key3);
                                                str_value4 = map.get(key4);
                                            }
                                            if (map.containsKey(key3)) {
                                                smallType.get(m).setPcbCapacityParamValue3(str_value3);
                                            }
                                            if (map.containsKey(key4)) {
                                                smallType.get(m).setPcbCapacityParamValue4(str_value4);
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return params;
    }

    @Override
    public List<PcbCapacityParamHistory> getChildrenWithDataHistory(Integer id, Integer pcbFactoryId, Integer valueType, String version) {
        System.out.println(new Date() + " 000");
        List<PcbCapacityParamHistory> params = getChildrenByIdHistory(id, version);
        System.out.println(new Date() + " 0005");
        Map<String, String> map = new HashMap<>();
        if (valueType == 1) {
            PcbCapacityDataHistory2 search1 = new PcbCapacityDataHistory2();
            search1.setPcbFactoryId(pcbFactoryId);
            search1.setPcbParamValueType(1);
            List<PcbCapacityDataHistory2> data1 = pcbCapacityDataHistory2Dao.getAllByLimit(search1);
            PcbCapacityDataHistory2 search2 = new PcbCapacityDataHistory2();
            search2.setPcbFactoryId(pcbFactoryId);
            search2.setPcbParamValueType(2);
            List<PcbCapacityDataHistory2> data2 = pcbCapacityDataHistory2Dao.getAllByLimit(search2);

            for (int i = 0; i < data1.size(); i++) {
                map.put(data1.get(i).getPcbParamKey(), data1.get(i).getPcbParamValue());
            }
            for (int i = 0; i < data2.size(); i++) {
                map.put(data2.get(i).getPcbParamKey(), data2.get(i).getPcbParamValue());
            }
        }
        if (valueType == 3) {
            PcbCapacityDataHistory2 search3 = new PcbCapacityDataHistory2();
            search3.setPcbFactoryId(pcbFactoryId);
            search3.setPcbParamValueType(3);
            PcbCapacityDataHistory2 search4 = new PcbCapacityDataHistory2();
            search4.setPcbFactoryId(pcbFactoryId);
            search4.setPcbParamValueType(4);
            System.out.println(new Date() + " 001");
            List<PcbCapacityDataHistory2> data3 = pcbCapacityDataHistory2Dao.getAllByLimit(search3);
            System.out.println(new Date() + " 002");
            List<PcbCapacityDataHistory2> data4 = pcbCapacityDataHistory2Dao.getAllByLimit(search4);

            for (int i = 0; i < data3.size(); i++) {
                map.put(data3.get(i).getPcbParamKey(), data3.get(i).getPcbParamValue());
            }
            for (int i = 0; i < data4.size(); i++) {
                map.put(data4.get(i).getPcbParamKey(), data4.get(i).getPcbParamValue());
            }
            System.out.println(new Date() + " 003");
        }
        System.out.println(new Date() + " 111");
        for (int i = 0; i < params.size(); i++) {
            if (!StringUtils.isBlank(params.get(i).getRemarkPic())) {
                params.get(i).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(params.get(i).getRemarkPic()));
            }
            List<PcbCapacityParamHistory> categorys = params.get(i).getChildren();
            if (categorys != null) {
                for (int j = 0; j < categorys.size(); j++) {
                    if (!StringUtils.isBlank(categorys.get(j).getRemarkPic())) {
                        categorys.get(j).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(categorys.get(j).getRemarkPic()));
                    }
                    List<PcbCapacityParamHistory> bigType = categorys.get(j).getChildren();
                    if (bigType != null) {
                        for (int k = 0; k < bigType.size(); k++) {
                            if (!StringUtils.isBlank(bigType.get(k).getRemarkPic())) {
                                bigType.get(k).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(bigType.get(k).getRemarkPic()));
                            }
                            List<PcbCapacityParamHistory> smallType = bigType.get(k).getChildren();
                            if (smallType != null) {
                                for (int m = 0; m < smallType.size(); m++) {
                                    if (!StringUtils.isBlank(smallType.get(m).getRemarkPic())) {
                                        smallType.get(m).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(smallType.get(m).getRemarkPic()));
                                    }
                                    if (!isBlank(smallType.get(m).getPcbCapacityParamKey())) {
                                        String key1 = smallType.get(m).getPcbCapacityParamKey();
                                        String key2 = smallType.get(m).getPcbCapacityParamKey2();
                                        String key3 = smallType.get(m).getPcbCapacityParamKey3();
                                        String key4 = smallType.get(m).getPcbCapacityParamKey4();
                                        if (valueType == 1) {
                                            String value1 = map.get(key1);
                                            String value2 = map.get(key2);
                                            String str_value1 = "";
                                            String str_value2 = "";
                                            if (smallType.get(m).getParamType() == 6)//公差
                                            {
                                                if (!StringUtils.isBlank(value1) && !StringUtils.isBlank(value2)) {
                                                    String[] arr = value1.split(",");
                                                    String[] arr2 = value2.split(",");
                                                    if (arr.length == 1) {
                                                        str_value1 = "±" + arr[0];
                                                    }
                                                    if (arr.length == 2) {
                                                        str_value1 = "+" + arr[0] + ",-" + arr[1];
                                                    }
                                                    if (arr2.length == 1) {
                                                        str_value2 = "±" + arr2[0];
                                                    }
                                                    if (arr2.length == 2) {
                                                        str_value2 = "+" + arr2[0] + ",-" + arr2[1];
                                                    }
                                                }
                                            } else {
                                                str_value1 = map.get(key1);
                                                str_value2 = map.get(key2);
                                            }
                                            if (map.containsKey(key1)) {
                                                smallType.get(m).setPcbCapacityParamValue(str_value1);
                                            }
                                            if (map.containsKey(key2)) {
                                                smallType.get(m).setPcbCapacityParamValue2(str_value2);
                                            }
                                        }
                                        if (valueType == 3) {
                                            String value3 = map.get(key3);
                                            String value4 = map.get(key4);
                                            String str_value3 = "";
                                            String str_value4 = "";
                                            if (smallType.get(m).getParamType() == 6)//公差
                                            {
                                                if (!StringUtils.isBlank(value3)) {
                                                    String[] arr3 = value3.split(",");
                                                    if (arr3.length == 1) {
                                                        str_value3 = "±" + arr3[0];
                                                    }
                                                    if (arr3.length == 2) {
                                                        str_value3 = "+" + arr3[0] + ",-" + arr3[1];
                                                    }
                                                }
                                                if (!StringUtils.isBlank(value4)) {
                                                    String[] arr4 = value4.split(",");
                                                    if (arr4.length == 1) {
                                                        str_value4 = "±" + arr4[0];
                                                    }
                                                    if (arr4.length == 2) {
                                                        str_value4 = "+" + arr4[0] + ",-" + arr4[1];
                                                    }
                                                }
                                            } else {
                                                str_value3 = map.get(key3);
                                                str_value4 = map.get(key4);
                                            }
                                            if (map.containsKey(key3)) {
                                                smallType.get(m).setPcbCapacityParamValue3(str_value3);
                                            }
                                            if (map.containsKey(key4)) {
                                                smallType.get(m).setPcbCapacityParamValue4(str_value4);
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println(new Date() + " 222");
        return params;
    }

    /*获取能力对比数据*/
    @Override
    public List<PcbCapacityParam> getCapacityComparison(Integer id, Integer pcbCapacityHistoryId, List<Integer> pcbFactoryIds) {

        List<PcbCapacityParam> params = getChildrenById(id, null, 1);
        Map<String, String> map = new HashMap<>();

        for (int m = 0; m < pcbFactoryIds.size(); m++) {
            Integer pcbFactoryId = pcbFactoryIds.get(m);
            List<PcbCapacityData> data1 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 1, null, null, null, null, null, null, null, null);
            for (int i = 0; i < data1.size(); i++) {
                map.put(pcbFactoryId + "-" + data1.get(i).getPcbParamKey(), data1.get(i).getPcbParamValue());
            }
            List<PcbCapacityData> data2 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 2, null, null, null, null, null, null, null, null);
            for (int i = 0; i < data2.size(); i++) {
                map.put(pcbFactoryId + "-" + data2.get(i).getPcbParamKey(), data2.get(i).getPcbParamValue());
            }
        }
        List<PcbCapacityData> data3 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, null, null, 3, null, null, null, null, null, null, null, null);
        for (int i = 0; i < data3.size(); i++) {
            map.put("H3C-" + data3.get(i).getPcbParamKey(), data3.get(i).getPcbParamValue());
        }
        List<PcbCapacityData> data4 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, null, null, 4, null, null, null, null, null, null, null, null);
        for (int i = 0; i < data4.size(); i++) {
            map.put("H3C-" + data4.get(i).getPcbParamKey(), data4.get(i).getPcbParamValue());
        }

        for (int i = 0; i < params.size(); i++) {
            List<PcbCapacityParam> categorys = params.get(i).getChildren();
            if (!StringUtils.isBlank(params.get(i).getRemarkPic())) {
                params.get(i).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(params.get(i).getRemarkPic()));
            }
            if (categorys != null) {
                for (int j = 0; j < categorys.size(); j++) {
                    if (!StringUtils.isBlank(categorys.get(j).getRemarkPic())) {
                        categorys.get(j).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(categorys.get(j).getRemarkPic()));
                    }
                    List<PcbCapacityParam> bigType = categorys.get(j).getChildren();
                    if (bigType != null) {
                        for (int k = 0; k < bigType.size(); k++) {
                            if (!StringUtils.isBlank(bigType.get(k).getRemarkPic())) {
                                bigType.get(k).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(bigType.get(k).getRemarkPic()));
                            }
                            List<PcbCapacityParam> smallType = bigType.get(k).getChildren();
                            if (smallType != null) {
                                for (int m = 0; m < smallType.size(); m++) {
                                    if (!StringUtils.isBlank(smallType.get(m).getRemarkPic())) {
                                        smallType.get(m).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(smallType.get(m).getRemarkPic()));
                                    }
                                    if (!isBlank(smallType.get(m).getPcbCapacityParamKey())) {
                                        String key1 = smallType.get(m).getPcbCapacityParamKey();
                                        String key2 = smallType.get(m).getPcbCapacityParamKey2();
                                        String key3 = smallType.get(m).getPcbCapacityParamKey3();
                                        String key4 = smallType.get(m).getPcbCapacityParamKey4();
                                        Map<String, ParamInfo> factoryDatas = new HashMap<>();
                                        ParamInfo paramInfo = new ParamInfo();
                                        paramInfo.setIsSatisfied(null);
                                        paramInfo.setIsSatisfied2(null);
                                        String H3CValue = map.get("H3C-" + key3);
                                        String H3CValue2 = map.get("H3C-" + key4);
                                        paramInfo.setValue(H3CValue);
                                        paramInfo.setValue2(H3CValue2);
                                        factoryDatas.put("H3C", paramInfo);
                                        for (int p = 0; p < pcbFactoryIds.size(); p++) {
                                            ParamInfo paramInfo2 = new ParamInfo();
                                            String factoryValue = map.get(pcbFactoryIds.get(p) + "-" + key1);
                                            String factoryValue2 = map.get(pcbFactoryIds.get(p) + "-" + key2);
                                            Integer ruleType = bigType.get(k).getRuleType();
                                            if (ruleType == null) {
                                                String pcbCapacityParamName = smallType.get(m).getPcbCapacityParamName();
                                                if (pcbCapacityParamName.contains("最大值")) {
                                                    ruleType = 1;
                                                }
                                                if (pcbCapacityParamName.contains("最小值")) {
                                                    ruleType = 2;
                                                }
                                            }
                                            Integer isSatisfied = checkIsSatisfied(ruleType, smallType.get(m).getParamType(), H3CValue, factoryValue);
                                            Integer isSatisfied2 = checkIsSatisfied(ruleType, smallType.get(m).getParamType(), H3CValue2, factoryValue2);
                                            paramInfo2.setIsSatisfied(isSatisfied);
                                            paramInfo2.setValue(factoryValue);
                                            paramInfo2.setIsSatisfied2(isSatisfied2);
                                            paramInfo2.setValue2(factoryValue2);
                                            factoryDatas.put(pcbFactoryIds.get(p).toString(), paramInfo2);
                                        }
                                        smallType.get(m).setFactoryDatas(factoryDatas);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return params;
    }

    /*获取能力对比历史数据*/
    @Override
    public List<PcbCapacityParamHistory> getCapacityComparisonHistory(Integer id, List<Integer> pcbFactoryIds, String version) {
        List<PcbCapacityParamHistory> params = getChildrenByIdHistory(id, version);
        Map<String, String> map = new HashMap<>();

        for (int m = 0; m < pcbFactoryIds.size(); m++) {
            Integer pcbFactoryId = pcbFactoryIds.get(m);
            PcbCapacityDataHistory2 search = new PcbCapacityDataHistory2();
            search.setPcbFactoryId(pcbFactoryId);
            search.setVersion(version);
            List<PcbCapacityDataHistory2> data1 = pcbCapacityDataHistory2Dao.getAllByLimit(search);
            for (int i = 0; i < data1.size(); i++) {
                map.put(pcbFactoryId + "-" + data1.get(i).getPcbParamKey(), data1.get(i).getPcbParamValue());
            }
        }
        PcbCapacityDataHistory2 search2 = new PcbCapacityDataHistory2();
        search2.setPcbFactoryId(null);
        search2.setVersion(version);
        search2.setPcbParamValueType(3);
        List<PcbCapacityDataHistory2> data3 = pcbCapacityDataHistory2Dao.getAllByLimit(search2);
        for (int i = 0; i < data3.size(); i++) {
            map.put("H3C-" + data3.get(i).getPcbParamKey(), data3.get(i).getPcbParamValue());
        }
        PcbCapacityDataHistory2 search4 = new PcbCapacityDataHistory2();
        search4.setPcbFactoryId(null);
        search4.setVersion(version);
        search4.setPcbParamValueType(4);
        List<PcbCapacityDataHistory2> data4 = pcbCapacityDataHistory2Dao.getAllByLimit(search4);
        for (int i = 0; i < data4.size(); i++) {
            map.put("H3C-" + data4.get(i).getPcbParamKey(), data4.get(i).getPcbParamValue());
        }
        try {
            for (int i = 0; i < params.size(); i++) {
                if (!StringUtils.isBlank(params.get(i).getRemarkPic())) {
                    params.get(i).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(params.get(i).getRemarkPic()));
                }
                List<PcbCapacityParamHistory> categorys = params.get(i).getChildren();
                if (categorys != null) {
                    for (int j = 0; j < categorys.size(); j++) {
                        if (!StringUtils.isBlank(categorys.get(j).getRemarkPic())) {
                            categorys.get(j).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(categorys.get(j).getRemarkPic()));
                        }
                        List<PcbCapacityParamHistory> bigType = categorys.get(j).getChildren();
                        if (bigType != null) {
                            for (int k = 0; k < bigType.size(); k++) {
                                if (!StringUtils.isBlank(bigType.get(k).getRemarkPic())) {
                                    bigType.get(k).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(bigType.get(k).getRemarkPic()));
                                }
                                List<PcbCapacityParamHistory> smallType = bigType.get(k).getChildren();
                                if (smallType != null) {
                                    for (int m = 0; m < smallType.size(); m++) {
                                        if (!StringUtils.isBlank(smallType.get(m).getRemarkPic())) {
                                            smallType.get(m).setImageBase64(CommonUtils.base64Prefix() + s3UploadFileService.getImageBase64FromUrl(smallType.get(m).getRemarkPic()));
                                        }
                                        if (!isBlank(smallType.get(m).getPcbCapacityParamKey())) {
                                            String key1 = smallType.get(m).getPcbCapacityParamKey();
                                            String key2 = smallType.get(m).getPcbCapacityParamKey2();
                                            String key3 = smallType.get(m).getPcbCapacityParamKey3();
                                            String key4 = smallType.get(m).getPcbCapacityParamKey4();
                                            Map<String, ParamInfo> factoryDatas = new HashMap<>();
                                            ParamInfo paramInfo = new ParamInfo();
                                            paramInfo.setIsSatisfied(null);
                                            paramInfo.setIsSatisfied2(null);
                                            String H3CValue = map.get("H3C-" + key3);
                                            String H3CValue2 = map.get("H3C-" + key4);
                                            paramInfo.setValue(H3CValue);
                                            paramInfo.setValue2(H3CValue2);
                                            factoryDatas.put("H3C", paramInfo);
                                            for (int p = 0; p < pcbFactoryIds.size(); p++) {
                                                ParamInfo paramInfo2 = new ParamInfo();
                                                String factoryValue = map.get(pcbFactoryIds.get(p) + "-" + key1);
                                                String factoryValue2 = map.get(pcbFactoryIds.get(p) + "-" + key2);
                                                Integer ruleType = bigType.get(k).getRuleType();
                                                if (ruleType == null) {
                                                    String pcbCapacityParamName = smallType.get(m).getPcbCapacityParamName();
                                                    if (pcbCapacityParamName.contains("最大值")) {
                                                        ruleType = 1;
                                                    }
                                                    if (pcbCapacityParamName.contains("最小值")) {
                                                        ruleType = 2;
                                                    }
                                                }
                                                Integer isSatisfied = checkIsSatisfied(ruleType, smallType.get(m).getParamType(), H3CValue, factoryValue);
                                                Integer isSatisfied2 = checkIsSatisfied(ruleType, smallType.get(m).getParamType(), H3CValue2, factoryValue2);
                                                paramInfo2.setIsSatisfied(isSatisfied);
                                                paramInfo2.setValue(factoryValue);
                                                paramInfo2.setIsSatisfied2(isSatisfied2);
                                                paramInfo2.setValue2(factoryValue2);
                                                factoryDatas.put(pcbFactoryIds.get(p).toString(), paramInfo2);
                                            }
                                            smallType.get(m).setFactoryDatas(factoryDatas);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        return params;
    }


    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result saveOldParamTemplate(String oldVersionYear, String oldVersionNum) {
        try {
            String userId = UserHeaderHolder.getUserId();

            List<PcbCapacityParamVersion> versions = pcbCapacityParamVersionDao.getByLimit(null, oldVersionYear, oldVersionNum, 1);
            {
//                final PcbCapacityParamVersion newestVersion = pcbCapacityParamService.getNewestVersion(null, 1);
                String str_newestVersion = oldVersionNum;
                String versionNum = str_newestVersion.replace("v", "").replace("V", "");
                Integer int_versionNum = Integer.parseInt(versionNum) + 1;
                if((versions == null || versions.stream().allMatch(Objects::isNull)) && "V01".equals(oldVersionNum))
                {
                    int_versionNum = Integer.parseInt(versionNum);
                }
                String new_versionNum = "V" + String.format("%02d", int_versionNum);
                PcbCapacityParamVersion pcbCapacityParamVersion = new PcbCapacityParamVersion();
                pcbCapacityParamVersion.setVersionYear(oldVersionYear);
                pcbCapacityParamVersion.setVersionNum(new_versionNum);
                pcbCapacityParamVersion.setCreateUser(userId);
                pcbCapacityParamVersion.setStatus(1);
                pcbCapacityParamVersion.setSort(100);
                pcbCapacityParamVersion.setCreateTime(new Date());
                pcbCapacityParamVersion.setVersionType(1);
                int count = pcbCapacityParamVersionDao.insert(pcbCapacityParamVersion);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力参数版本", 3, 1, new Date(), null, toJSONString(pcbCapacityParamVersion)));
                }
            }

            //先保存能力参数
            List<PcbCapacityParam> pcbCapacityParamListOld = pcbCapacityParamDao.getAllByLimit(null, null, null, null, null, null, null, null, null, null, null, null, null);
            List<PcbCapacityParamHistory> pcbCapacityParamHistoryList = new ArrayList<>();
            for (int i = 0; i < pcbCapacityParamListOld.size(); i++) {
                PcbCapacityParamHistory pcbCapacityParamHistory = new PcbCapacityParamHistory(pcbCapacityParamListOld.get(i));
                pcbCapacityParamHistory.setVersion(oldVersionYear + "_" + oldVersionNum);
                pcbCapacityParamHistoryList.add(pcbCapacityParamHistory);
            }
            if (pcbCapacityParamHistoryList.size() > 0) {
                int count = pcbCapacityParamHistoryDao.insertBatch(pcbCapacityParamHistoryList);
            }
            //再保存数据
            List<PcbCapacityDataHistory2> pcbCapacityDataHistory2List = new ArrayList<>();
            List<PcbCapacityData> pcbCapacityDataListOld = pcbCapacityDataDao.getById(null);
            for (int i = 0; i < pcbCapacityDataListOld.size(); i++) {
                PcbCapacityDataHistory2 pcbCapacityDataHistory2 = new PcbCapacityDataHistory2(pcbCapacityDataListOld.get(i));
                pcbCapacityDataHistory2.setVersion(oldVersionYear + "_" + oldVersionNum);
                pcbCapacityDataHistory2List.add(pcbCapacityDataHistory2);
            }
            if (pcbCapacityDataHistory2List.size() > 0) {
                int count = pcbCapacityDataHistory2Dao.insertBatch(pcbCapacityDataHistory2List);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }


    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result saveOldParamTemplate2(String newVersionYear, String newVersionNum) {
        try {
            PcbCapacityDataHistory2 search = new PcbCapacityDataHistory2();
            search.setVersion(newVersionYear + "_" + newVersionNum);
            final List<PcbCapacityDataHistory2> allByLimit = pcbCapacityDataHistory2Dao.getAllByLimit(search);
            if (allByLimit.size() > 0) {
                return ResultUtil.error(500, "该版本数据已存在", "", null);
            }
            String userId = UserHeaderHolder.getUserId();

            final PcbCapacityParamVersion newestVersion = getNewestVersion(null, 1);

            String oldVersionYear = newestVersion.getVersionYear();
            String oldVersionNum = newestVersion.getVersionNum();
            PcbCapacityParamVersion pcbCapacityParamVersion = new PcbCapacityParamVersion();
            if(!String.valueOf(Year.now()).equals(newVersionYear))
            {
                newVersionYear = String.valueOf(Year.now());
                newVersionNum = "V01";
            }
            pcbCapacityParamVersion.setVersionYear(newVersionYear);
            pcbCapacityParamVersion.setVersionNum(newVersionNum);
            pcbCapacityParamVersion.setCreateUser(userId);
            pcbCapacityParamVersion.setStatus(1);
            pcbCapacityParamVersion.setSort(100);
            pcbCapacityParamVersion.setCreateTime(new Date());
            pcbCapacityParamVersion.setVersionType(1);
            int count = pcbCapacityParamVersionDao.insert(pcbCapacityParamVersion);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力参数版本", 3, 1, new Date(), null, toJSONString(pcbCapacityParamVersion)));
            }


            //先保存能力参数
            List<PcbCapacityParam> pcbCapacityParamListOld = pcbCapacityParamDao.getAllByLimit(null, null, null, null, null, null, null, null, null, null, null, null, null);
            List<PcbCapacityParamHistory> pcbCapacityParamHistoryList = new ArrayList<>();
            for (int i = 0; i < pcbCapacityParamListOld.size(); i++) {
                PcbCapacityParamHistory pcbCapacityParamHistory = new PcbCapacityParamHistory(pcbCapacityParamListOld.get(i));
                pcbCapacityParamHistory.setVersion(oldVersionYear + "_" + oldVersionNum);
                pcbCapacityParamHistoryList.add(pcbCapacityParamHistory);
            }
            if (pcbCapacityParamHistoryList.size() > 0) {
                count = pcbCapacityParamHistoryDao.insertBatch(pcbCapacityParamHistoryList);
            }
            //再保存数据
            List<PcbCapacityDataHistory2> pcbCapacityDataHistory2List = new ArrayList<>();
            List<PcbCapacityData> pcbCapacityDataListOld = pcbCapacityDataDao.getById(null);
            for (int i = 0; i < pcbCapacityDataListOld.size(); i++) {
                PcbCapacityDataHistory2 pcbCapacityDataHistory2 = new PcbCapacityDataHistory2(pcbCapacityDataListOld.get(i));
                pcbCapacityDataHistory2.setVersion(oldVersionYear + "_" + oldVersionNum);
                pcbCapacityDataHistory2List.add(pcbCapacityDataHistory2);
            }
            if (pcbCapacityDataHistory2List.size() > 0) {
                count = pcbCapacityDataHistory2Dao.insertBatch(pcbCapacityDataHistory2List);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }


    }

    @Override
    public List<PcbCapacityParamVersion> getVersionList(String versionYear, Integer versionType) {
        return pcbCapacityParamVersionDao.getByLimit(null, versionYear, null, versionType);
    }

    @Override
    public List<PcbCapacityParamVersion> getVersionListByTemplateStatus(String versionYear, Integer versionType) {
        PcbCapacityDataApprove systemStatus = pcbCapacityDataApproveDao.getSystemStatus();
        if (systemStatus.getApproveStatus().equals("已分发") || versionType == 2) {
            return pcbCapacityParamVersionDao.getByLimit(null, versionYear, null, versionType);
        } else {
            List<PcbCapacityParamVersion> pcbCapacityParamVersionList = pcbCapacityParamVersionDao.getByLimit(null, versionYear, null, versionType);
            if (pcbCapacityParamVersionList.size() > 0) {
                pcbCapacityParamVersionList.remove(pcbCapacityParamVersionList.size() - 1);
            }
            return pcbCapacityParamVersionList;
        }
    }

    @Override
    public Result checkOldParamTemplate(String oldVersionYear, String oldVersionNum, Integer versionType) {
        List<PcbCapacityParamVersion> versions = pcbCapacityParamVersionDao.getByLimit(null, oldVersionYear, oldVersionNum, versionType);
        if (versions != null && versions.size() > 0) {
            return ResultUtil.success(true);
        } else {
            return ResultUtil.success(false);
        }
    }

    @Value("${personal.config.file.file-save-url}")
    private String rootPath;

    @Override
    /* 导出能力对比数据 */
    public Result outputCapacityComparison(Integer id, Integer pcbCapacityHistoryId, List<Integer> pcbFactoryIds, String version, Integer type) throws IOException {
//        int type = 1;//1只输出大批量，2只输出小批量，3输出大批量和小批量，4 输出厂家的大批量和小批量，H3C要求值不输出
        List<PcbCapacityParamHistory> capacityComparisonData = new ArrayList();
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            final PcbCapacityParamVersion newestVersion = getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> childrenById = getCapacityComparison(id, pcbCapacityHistoryId, pcbFactoryIds);
                    for (int i = 0; i < childrenById.size(); i++) {
                        capacityComparisonData.add(new PcbCapacityParamHistory(childrenById.get(i)));
                    }
                } else {
                    capacityComparisonData = getCapacityComparisonHistory(0, pcbFactoryIds, version);
                }
            } else {
                List<PcbCapacityParam> childrenById = getCapacityComparison(id, pcbCapacityHistoryId, pcbFactoryIds);
                for (int i = 0; i < childrenById.size(); i++) {
                    capacityComparisonData.add(new PcbCapacityParamHistory(childrenById.get(i)));
                }
            }
        }

        int rowIndex = 5;
        int startIndex0 = 2;
        int startIndex1 = 2;
        int startIndex2 = 2;
        try {
            List<PcbSonFactoryInfo> factoryInfos = new ArrayList<>();
            for (int i = 0; i < pcbFactoryIds.size(); i++) {
                Integer idi = pcbFactoryIds.get(i);
                PcbSonFactoryInfo sonFactoryInfo = pcbSonFactoryInfoDao.getById(idi);
                factoryInfos.add(sonFactoryInfo);
            }
            int columnCount = 7 + pcbFactoryIds.size() * 2;
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("Sheet1");

            XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
            setBorder.setBorderBottom(BorderStyle.THIN);
            setBorder.setBorderLeft(BorderStyle.THIN);
            setBorder.setBorderRight(BorderStyle.THIN);
            setBorder.setBorderTop(BorderStyle.THIN);
            setBorder.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder.setAlignment(HorizontalAlignment.LEFT);
            //创建字体 加粗
            XSSFFont font = (XSSFFont) workbook.createFont();
            font.setBold(true);
            font.setFontHeight(11);
            setBorder.setFont(font);

            XSSFCellStyle setFont = (XSSFCellStyle) workbook.createCellStyle();
            setFont.setFont(font);

            XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
            setBorder2.setBorderBottom(BorderStyle.THIN);
            setBorder2.setBorderLeft(BorderStyle.THIN);
            setBorder2.setBorderRight(BorderStyle.THIN);
            setBorder2.setBorderTop(BorderStyle.THIN);
            setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
            setBorder2.setAlignment(HorizontalAlignment.LEFT);

            XSSFCellStyle styleRed = (XSSFCellStyle) workbook.createCellStyle();
            styleRed.setBorderBottom(BorderStyle.THIN);
            styleRed.setBorderLeft(BorderStyle.THIN);
            styleRed.setBorderRight(BorderStyle.THIN);
            styleRed.setBorderTop(BorderStyle.THIN);
            styleRed.setVerticalAlignment(VerticalAlignment.CENTER);
            styleRed.setAlignment(HorizontalAlignment.LEFT);
            styleRed.setFillForegroundColor(IndexedColors.RED.getIndex());
            styleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            XSSFCellStyle styleGreen = (XSSFCellStyle) workbook.createCellStyle();
            styleGreen.setBorderBottom(BorderStyle.THIN);
            styleGreen.setBorderLeft(BorderStyle.THIN);
            styleGreen.setBorderRight(BorderStyle.THIN);
            styleGreen.setBorderTop(BorderStyle.THIN);
            styleGreen.setVerticalAlignment(VerticalAlignment.CENTER);
            styleGreen.setAlignment(HorizontalAlignment.LEFT);
            styleGreen.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            styleGreen.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
            Row rowTR = sheet.createRow(0);
            Cell cellTR0 = rowTR.createCell(0);
            cellTR0.setCellValue("下载时间：");
            cellTR0.setCellStyle(setFont);
            Cell cellTR1 = rowTR.createCell(1);
            cellTR1.setCellValue(format2.format(new Date()));
            Cell cellTR2 = rowTR.createCell(2);
            cellTR2.setCellValue("下载人员：");
            cellTR2.setCellStyle(setFont);
            Cell cellTR3 = rowTR.createCell(3);
            cellTR3.setCellValue(UserHeaderHolder.getDomainAccount());
            Cell cellTR4 = rowTR.createCell(4);
            cellTR4.setCellValue("版本：");
            cellTR4.setCellStyle(setFont);
            Cell cellTR5 = rowTR.createCell(5);
            cellTR5.setCellValue(StringUtils.isBlank(version) ? "" : version);


            Row rowT0 = sheet.createRow(1);
            Cell cell8 = rowT0.createCell(0);
            cell8.setCellValue("PCB能力项");
            cell8.setCellStyle(setBorder);
            Cell cell81 = rowT0.createCell(1);
            cell81.setCellStyle(setBorder);
            Cell cell82 = rowT0.createCell(2);
            cell82.setCellStyle(setBorder);
            Cell cell83 = rowT0.createCell(3);
            cell83.setCellStyle(setBorder);
            // 合并第1行的第1个单元格到第3个单元格
//            CellRangeAddress region0 = new CellRangeAddress(0, 0, 0, 3);
//            sheet.addMergedRegion(region0);
            Row rowT1 = sheet.createRow(2);
            Cell cell = rowT1.createCell(0);
            cell.setCellValue("类型");
            cell.setCellStyle(setBorder);
            Cell cell2 = rowT1.createCell(1);
            cell2.setCellValue("类别");
            cell2.setCellStyle(setBorder);
            Cell cell3 = rowT1.createCell(2);
            cell3.setCellStyle(setBorder);
            cell3.setCellValue("大类");
            Cell cell4 = rowT1.createCell(3);
            cell4.setCellStyle(setBorder);
            cell4.setCellValue("小类");
            Cell cell5 = rowT1.createCell(4);
            cell5.setCellStyle(setBorder);
            cell5.setCellValue("H3C设计能力要求");
            Cell cell55 = rowT1.createCell(5);
            cell55.setCellStyle(setBorder);

            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoService.getBySonList(pcbFactoryIds, null);
            int columIndex = 6;
            Row rowT2 = sheet.createRow(3);
            final Cell cell14 = rowT2.createCell(1);
            cell14.setCellStyle(setBorder);
            final Cell cell15 = rowT2.createCell(2);
            cell15.setCellStyle(setBorder);
            final Cell cell16 = rowT2.createCell(3);
            cell16.setCellStyle(setBorder);
            final Cell cell17 = rowT2.createCell(4);
            cell17.setCellStyle(setBorder);
            final Cell cell18 = rowT2.createCell(5);
            cell18.setCellStyle(setBorder);

            Row rowT3 = sheet.createRow(4);
            final Cell cell34 = rowT3.createCell(1);
            cell34.setCellStyle(setBorder);
            final Cell cell35 = rowT3.createCell(2);
            cell35.setCellStyle(setBorder);
            final Cell cell36 = rowT3.createCell(3);
            cell36.setCellStyle(setBorder);
            final Cell cell9 = rowT3.createCell(4);
            cell9.setCellValue("量产能力");
            cell9.setCellStyle(setBorder2);
            final Cell cell10 = rowT3.createCell(5);
            cell10.setCellValue("小批量能力");
            cell10.setCellStyle(setBorder2);
            List<Integer> pcbFactoryIds_new = new ArrayList<>();
            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++) {
                Cell celli = rowT1.createCell(columIndex);
                celli.setCellStyle(setBorder);
                celli.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyName());
                int startIndexT = columIndex;
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null && sonFactoryInfos.size() > 0) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        Cell cell6 = rowT2.createCell(columIndex);
                        cell6.setCellValue(sonFactoryInfos.get(j).getSonFactoryName());
                        cell6.setCellStyle(setBorder);
                        Cell cell1 = rowT3.createCell(columIndex);
                        cell1.setCellValue("量产能力");
                        cell1.setCellStyle(setBorder2);
                        if (j != 0) {
                            Cell cell122 = rowT1.createCell(columIndex);
                            cell122.setCellStyle(setBorder);
                        }
                        columIndex++;
                        final Cell cell11 = rowT2.createCell(columIndex);
                        cell11.setCellStyle(setBorder);
                        final Cell cell12 = rowT1.createCell(columIndex);
                        cell12.setCellStyle(setBorder);
                        CellRangeAddress region2 = new CellRangeAddress(2, 2, columIndex - 1, columIndex);
                        sheet.addMergedRegion(region2);
                        Cell cell7 = rowT3.createCell(columIndex);
                        cell7.setCellValue("小批量能力");
                        cell7.setCellStyle(setBorder2);
                        columIndex++;
                        pcbFactoryIds_new.add(sonFactoryInfos.get(j).getPcbSonFactoryId());
                    }
                    CellRangeAddress region3 = new CellRangeAddress(1, 1, startIndexT, columIndex - 1);
                    if (columIndex - 1 > startIndexT) {
                        sheet.addMergedRegion(region3);
                    }
                } else {
                    columIndex++;
                }
            }
            for (int i = 0; i < capacityComparisonData.size(); i++) {
                startIndex0 = rowIndex;
                Row row = sheet.createRow(rowIndex);
                rowIndex++;
                Cell cell00 = row.createCell(0);
                cell00.setCellValue(capacityComparisonData.get(i).getPcbCapacityParamName());

                List<PcbCapacityParamHistory> categorys = capacityComparisonData.get(i).getChildren();
                if (categorys != null) {
                    for (int j = 0; j < categorys.size(); j++) {
                        if (j == 0) {
                            startIndex1 = startIndex0;
                        } else {
                            startIndex1 = rowIndex;
                        }

                        Row row2;
                        if (j == 0) {
                            row2 = row;
                        } else {
                            row2 = sheet.createRow(rowIndex);
                            rowIndex++;
                        }
                        Cell cell11 = row2.createCell(1);
                        cell11.setCellValue(categorys.get(j).getPcbCapacityParamName());
                        List<PcbCapacityParamHistory> bigType = categorys.get(j).getChildren();
                        if (bigType != null) {
                            for (int k = 0; k < bigType.size(); k++) {
                                if (k > 0) {
                                    startIndex2 = rowIndex;
                                } else {
                                    startIndex2 = startIndex1;
                                }
                                Row row3;
                                if (k == 0) {
                                    row3 = row2;
                                } else {
                                    row3 = sheet.createRow(rowIndex);
                                    rowIndex++;
                                }
                                Cell cell22 = row3.createCell(2);
                                cell22.setCellValue(bigType.get(k).getPcbCapacityParamName());
//                                cell22.setCellStyle(setBorder);
                                List<PcbCapacityParamHistory> smallType = bigType.get(k).getChildren();
                                if (smallType != null) {
                                    for (int m = 0; m < smallType.size(); m++) {
                                        Row row4;
//                                    List<String> datas = smallType.get(i).getFactoryDatas();
                                        Map<String, ParamInfo> factoryDatas = smallType.get(m).getFactoryDatas();
                                        // 创建行和单元格对象
                                        if (m > 0) {
                                            row4 = sheet.createRow(rowIndex);
                                            rowIndex++;
                                        } else {
                                            row4 = row3;
                                        }
                                        Cell cell1 = row4.createCell(3);
                                        cell1.setCellValue(smallType.get(m).getPcbCapacityParamName());
                                        Cell cell6 = row4.createCell(4);
                                        cell6.setCellValue(factoryDatas.get("H3C").getValue());
                                        Cell cell12 = row4.createCell(5);
                                        cell12.setCellValue(factoryDatas.get("H3C").getValue2());
                                        int colIndex2 = 6;
                                        for (int l = 0; l < pcbFactoryIds_new.size(); l++) {
                                            Cell cell7 = row4.createCell(colIndex2);
                                            colIndex2++;
                                            Cell cell13 = row4.createCell(colIndex2);
                                            colIndex2++;
                                            Integer satisfied_value = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getIsSatisfied();
                                            Integer satisfied_value2 = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getIsSatisfied2();
                                            String value = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getValue();
                                            String value2 = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getValue2();
                                            cell7.setCellValue(value);
                                            cell13.setCellValue(value2);
                                            if (!StringUtils.isBlank(value)) {
                                                if (satisfied_value != null) {
                                                    if (satisfied_value == 1) {
                                                        cell7.setCellStyle(styleGreen);
                                                    } else {
                                                        cell7.setCellStyle(styleRed);
                                                    }
                                                }

                                            } else {
                                                cell7.setCellStyle(setBorder);
                                            }
                                            if (!StringUtils.isBlank(value2)) {
                                                if (satisfied_value2 != null) {
                                                    if (satisfied_value2 == 1) {
                                                        cell13.setCellStyle(styleGreen);
                                                    } else {
                                                        cell13.setCellStyle(styleRed);
                                                    }
                                                }

                                            } else {
                                                cell13.setCellStyle(setBorder);
                                            }
                                        }

                                        Cell cellRemark = row4.createCell(colIndex2);
                                        cellRemark.setCellValue(getStringParamType(smallType.get(m).getParamType()));
                                    }
                                } else {
                                    Cell cell1 = row3.createCell(4);
                                    Cell cell6 = row3.createCell(5);
                                    int colIndex2 = 6;
                                    for (int l = 0; l < pcbFactoryIds.size(); l++) {
                                        Cell cell7 = row3.createCell(colIndex2);
                                        colIndex2++;
                                        final Cell cell12 = row3.createCell(colIndex2);
                                        colIndex2++;
                                        Cell cellRemark = row3.createCell(colIndex2);
                                    }
                                }
                                CellRangeAddress region3 = new CellRangeAddress(startIndex2, rowIndex - 1, 2, 2);
                                if (rowIndex - 1 > startIndex2) {
                                    sheet.addMergedRegion(region3);
                                }
                            }
                        }
                        CellRangeAddress region2 = new CellRangeAddress(startIndex1, rowIndex - 1, 1, 1);
                        if (rowIndex - 1 > startIndex1) {
                            sheet.addMergedRegion(region2);
                        }
                    }
                }
                CellRangeAddress region = new CellRangeAddress(startIndex0, rowIndex - 1, 0, 0);
                if (rowIndex - 1 > startIndex0) {
                    sheet.addMergedRegion(region);
                }
            }

            Cell cell06 = rowT1.createCell(columnCount - 1);
            cell06.setCellStyle(setBorder);
            cell06.setCellValue("说明");
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 5));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, columnCount - 1, columnCount - 1));

            for (int i = 4; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell celli = row.getCell(j);
                    if (celli == null) {
                        celli = row.createCell(j);
                        celli.setCellStyle(setBorder2);
                    } else {
                        if (celli.getCellStyle() == null) {
                            celli.setCellStyle(setBorder2);
                        } else {
                            if (celli.getCellStyle().getFillForegroundColor() != IndexedColors.GREEN.getIndex()
                                    && celli.getCellStyle().getFillForegroundColor() != IndexedColors.RED.getIndex()) {
                                celli.setCellStyle(setBorder2);
                            }
                        }
                    }


                }
            }
            sheet.setColumnWidth(0, 15 * 256);
            sheet.setColumnWidth(1, 15 * 256);
            sheet.setColumnWidth(2, 15 * 256);
            sheet.setColumnWidth(3, 15 * 256);
            sheet.setColumnWidth(4, 12 * 256);
            sheet.setColumnWidth(5, 12 * 256);
            sheet.setColumnWidth(columnCount - 1, 20 * 256);
            if (type != null && type == 1) {
                sheet.setColumnHidden(5, true);
            }
            if (type != null && type == 2) {
                sheet.setColumnHidden(4, true);
            }
            for (int i = 0; i < factoryInfos.size() * 2; i++) {
                sheet.setColumnWidth(6 + i, 12 * 256);

                if (type != null && type == 1) {
                    if ((6 + i) % 2 == 1) {
                        sheet.setColumnHidden(6 + i, true);
                    }
                }
                if (type != null && type == 2) {
                    if ((6 + i) % 2 == 0) {
                        sheet.setColumnHidden(6 + i, true);
                    }
                }
            }
            // 导出Excel文件
            String filename = "能力数据" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            String filePath = rootPath + "pcb\\" + format + "\\" + filename + ".xlsx";
            File folder = new File(rootPath + "pcb\\" + format);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    /* 导出厂家能力数据 */
    public Result outputCapacityComparisonFactory(Integer id, Integer pcbCapacityHistoryId, List<Integer> pcbFactoryIds, String version) throws IOException {
        List<PcbCapacityParamHistory> capacityComparisonData = new ArrayList();
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        } else {
            final PcbCapacityParamVersion newestVersion = getNewestVersion(null, 1);
            String str_newestVersion = "";
            if (newestVersion != null) {
                str_newestVersion = newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum();
                if (version.equals(str_newestVersion)) {
                    List<PcbCapacityParam> childrenById = getCapacityComparison(id, pcbCapacityHistoryId, pcbFactoryIds);
                    for (int i = 0; i < childrenById.size(); i++) {
                        capacityComparisonData.add(new PcbCapacityParamHistory(childrenById.get(i)));
                    }
                } else {
                    capacityComparisonData = getCapacityComparisonHistory(0, pcbFactoryIds, version);
                }
            } else {
                List<PcbCapacityParam> childrenById = getCapacityComparison(id, pcbCapacityHistoryId, pcbFactoryIds);
                for (int i = 0; i < childrenById.size(); i++) {
                    capacityComparisonData.add(new PcbCapacityParamHistory(childrenById.get(i)));
                }
            }
        }

        int rowIndex = 5;
        int startIndex0 = 2;
        int startIndex1 = 2;
        int startIndex2 = 2;
        try {
            List<PcbSonFactoryInfo> factoryInfos = new ArrayList<>();
            for (int i = 0; i < pcbFactoryIds.size(); i++) {
                Integer idi = pcbFactoryIds.get(i);
                PcbSonFactoryInfo sonFactoryInfo = pcbSonFactoryInfoDao.getById(idi);
                factoryInfos.add(sonFactoryInfo);
            }
            int columnCount = 4 + pcbFactoryIds.size() * 3;
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");
            XSSFCellStyle setBorder = getStyle1(workbook);
            XSSFCellStyle setBorder2 = getStyle2(workbook);
            XSSFCellStyle setFont = getStyleFont(workbook);
            XSSFCellStyle styleGreen = getStyleColor(workbook, IndexedColors.GREEN.getIndex());
            XSSFCellStyle styleRed = getStyleColor(workbook, IndexedColors.RED.getIndex());

            Row rowT0 = sheet.createRow(1);
            Cell cell8 = rowT0.createCell(0);
            cell8.setCellValue("PCB能力项");
            cell8.setCellStyle(setBorder);
            Cell cell81 = rowT0.createCell(1);
            cell81.setCellStyle(setBorder);
            Cell cell82 = rowT0.createCell(2);
            cell82.setCellStyle(setBorder);
            Cell cell83 = rowT0.createCell(3);
            cell83.setCellStyle(setBorder);
            // 合并第1行的第1个单元格到第3个单元格
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            Row rowTR = sheet.createRow(0);
            Cell cellTR0 = rowTR.createCell(0);
            cellTR0.setCellValue("下载时间：");
            cellTR0.setCellStyle(setFont);
            Cell cellTR1 = rowTR.createCell(1);
            cellTR1.setCellValue(format.format(new Date()));
            Cell cellTR2 = rowTR.createCell(2);
            cellTR2.setCellValue("下载人员：");
            cellTR2.setCellStyle(setFont);
            Cell cellTR3 = rowTR.createCell(3);
            cellTR3.setCellValue(UserHeaderHolder.getDomainAccount());
            Cell cellTR4 = rowTR.createCell(4);
            cellTR4.setCellValue("版本：");
            cellTR4.setCellStyle(setFont);
            Cell cellTR5 = rowTR.createCell(5);
            cellTR5.setCellValue(StringUtils.isBlank(version) ? "" : version);
            CellRangeAddress region0 = new CellRangeAddress(1, 1, 0, 3);
            sheet.addMergedRegion(region0);
            Row rowT1 = sheet.createRow(2);
            Cell cell = rowT1.createCell(0);
            cell.setCellValue("类型");
            cell.setCellStyle(setBorder);
            Cell cell2 = rowT1.createCell(1);
            cell2.setCellValue("类别");
            cell2.setCellStyle(setBorder);
            Cell cell3 = rowT1.createCell(2);
            cell3.setCellStyle(setBorder);
            cell3.setCellValue("大类");
            Cell cell4 = rowT1.createCell(3);
            cell4.setCellStyle(setBorder);
            cell4.setCellValue("小类");
            Cell cell06 = rowT1.createCell(6);
            cell06.setCellStyle(setBorder);
            cell06.setCellValue("说明");
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoService.getBySonList(pcbFactoryIds, null);
            int columIndex = 4;
            Row rowT2 = sheet.createRow(3);
            final Cell cell14 = rowT2.createCell(1);
            cell14.setCellStyle(setBorder);
            final Cell cell15 = rowT2.createCell(2);
            cell15.setCellStyle(setBorder);
            final Cell cell16 = rowT2.createCell(3);
            cell16.setCellStyle(setBorder);
            final Cell cell166 = rowT2.createCell(6);
            cell166.setCellStyle(setBorder);
            Row rowT3 = sheet.createRow(4);
            final Cell cell34 = rowT3.createCell(1);
            cell34.setCellStyle(setBorder);
            final Cell cell35 = rowT3.createCell(2);
            cell35.setCellStyle(setBorder);
            final Cell cell36 = rowT3.createCell(3);
            cell36.setCellStyle(setBorder);
            final Cell cell366 = rowT3.createCell(6);
            cell366.setCellStyle(setBorder);
            Map<String, String> mapRemark = new HashMap<>();
            List<PcbCapacityParam> paramList = pcbCapacityParamDao.getParamList(null, 3, null, null, 1);
            for (int i = 0; i < paramList.size(); i++) {
                String remark = getStringParamType(paramList.get(i).getParamType()) + "," + (paramList.get(i).getRemark() == null ? "" : paramList.get(i).getRemark());
                mapRemark.put(paramList.get(i).getPcbCapacityParamKey(), remark);
                mapRemark.put(paramList.get(i).getPcbCapacityParamKey2(), remark);
                mapRemark.put(paramList.get(i).getPcbCapacityParamKey3(), remark);
                mapRemark.put(paramList.get(i).getPcbCapacityParamKey4(), remark);
            }
            List<Integer> pcbFactoryIds_new = new ArrayList<>();
            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++) {
                Cell celli = rowT1.createCell(columIndex);
                celli.setCellStyle(setBorder);
                celli.setCellValue(pcbParentFactoryInfoList.get(i).getCompanyName());
                int startIndexT = columIndex;
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null && sonFactoryInfos.size() > 0) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        Cell cell6 = rowT2.createCell(columIndex);
                        cell6.setCellValue(sonFactoryInfos.get(j).getSonFactoryName());
                        cell6.setCellStyle(setBorder);
                        Cell cell1 = rowT3.createCell(columIndex);
                        cell1.setCellValue("量产能力");
                        cell1.setCellStyle(setBorder2);
                        if (j != 0) {
                            Cell cell122 = rowT1.createCell(columIndex);
                            cell122.setCellStyle(setBorder);
                        }
                        columIndex++;
                        final Cell cell11 = rowT2.createCell(columIndex);
                        cell11.setCellStyle(setBorder);
                        final Cell cell12 = rowT1.createCell(columIndex);
                        cell12.setCellStyle(setBorder);
                        CellRangeAddress region2 = new CellRangeAddress(2, 2, columIndex - 1, columIndex);
                        sheet.addMergedRegion(region2);
                        Cell cell7 = rowT3.createCell(columIndex);
                        cell7.setCellValue("小批量能力");
                        cell7.setCellStyle(setBorder2);
                        columIndex++;
                        pcbFactoryIds_new.add(sonFactoryInfos.get(j).getPcbSonFactoryId());
                    }
                    CellRangeAddress region3 = new CellRangeAddress(1, 1, startIndexT, columIndex - 1);
                    if (columIndex - 1 > startIndexT) {
                        sheet.addMergedRegion(region3);
                    }
                } else {
                    columIndex++;
                }
            }
            for (int i = 0; i < capacityComparisonData.size(); i++) {
                startIndex0 = rowIndex;
                Row row = sheet.createRow(rowIndex);
                rowIndex++;
                Cell cell00 = row.createCell(0);
                cell00.setCellValue(capacityComparisonData.get(i).getPcbCapacityParamName());

                List<PcbCapacityParamHistory> categorys = capacityComparisonData.get(i).getChildren();
                if (categorys != null) {
                    for (int j = 0; j < categorys.size(); j++) {
                        if (j == 0) {
                            startIndex1 = startIndex0;
                        } else {
                            startIndex1 = rowIndex;
                        }

                        Row row2;
                        if (j == 0) {
                            row2 = row;
                        } else {
                            row2 = sheet.createRow(rowIndex);
                            rowIndex++;
                        }
                        Cell cell11 = row2.createCell(1);
                        cell11.setCellValue(categorys.get(j).getPcbCapacityParamName());
                        List<PcbCapacityParamHistory> bigType = categorys.get(j).getChildren();
                        if (bigType != null) {
                            for (int k = 0; k < bigType.size(); k++) {
                                if (k > 0) {
                                    startIndex2 = rowIndex;
                                } else {
                                    startIndex2 = startIndex1;
                                }
                                Row row3;
                                if (k == 0) {
                                    row3 = row2;
                                } else {
                                    row3 = sheet.createRow(rowIndex);
                                    rowIndex++;
                                }
                                Cell cell22 = row3.createCell(2);
                                cell22.setCellValue(bigType.get(k).getPcbCapacityParamName());
                                List<PcbCapacityParamHistory> smallType = bigType.get(k).getChildren();
                                if (smallType != null) {
                                    for (int m = 0; m < smallType.size(); m++) {
                                        Row row4;
//                                    List<String> datas = smallType.get(i).getFactoryDatas();
                                        Map<String, ParamInfo> factoryDatas = smallType.get(m).getFactoryDatas();
                                        // 创建行和单元格对象
                                        if (m > 0) {
                                            row4 = sheet.createRow(rowIndex);
                                            rowIndex++;
                                        } else {
                                            row4 = row3;
                                        }
                                        Cell cell1 = row4.createCell(3);
                                        cell1.setCellValue(smallType.get(m).getPcbCapacityParamName());
                                        int colIndex2 = 4;
                                        for (int l = 0; l < pcbFactoryIds_new.size(); l++) {
                                            Cell cell7 = row4.createCell(colIndex2);
                                            colIndex2++;
                                            Cell cell13 = row4.createCell(colIndex2);
                                            colIndex2++;
                                            Integer satisfied_value = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getIsSatisfied();
                                            Integer satisfied_value2 = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getIsSatisfied2();
                                            String value = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getValue();
                                            String value2 = factoryDatas.get(pcbFactoryIds_new.get(l).toString()).getValue2();
                                            cell7.setCellValue(value);
                                            cell13.setCellValue(value2);
                                            if (!StringUtils.isBlank(value)) {
                                                if (satisfied_value != null) {
                                                    if (satisfied_value == 1) {
                                                        cell7.setCellStyle(styleGreen);
                                                    } else {
                                                        cell7.setCellStyle(styleRed);
                                                    }
                                                }

                                            } else {
                                                cell7.setCellStyle(setBorder);
                                            }
                                            if (!StringUtils.isBlank(value2)) {
                                                if (satisfied_value2 != null) {
                                                    if (satisfied_value2 == 1) {
                                                        cell13.setCellStyle(styleGreen);
                                                    } else {
                                                        cell13.setCellStyle(styleRed);
                                                    }
                                                }

                                            } else {
                                                cell13.setCellStyle(setBorder);
                                            }
                                            Cell cellRemark = row4.createCell(colIndex2);
                                            cellRemark.setCellValue(mapRemark.get(smallType.get(m).getPcbCapacityParamKey()));
                                            colIndex2++;
                                        }
                                    }
                                } else {
                                    Cell cell1 = row3.createCell(4);
                                    Cell cell6 = row3.createCell(5);
                                    int colIndex2 = 4;
                                    for (int l = 0; l < pcbFactoryIds.size(); l++) {
                                        Cell cell7 = row3.createCell(colIndex2);
                                        colIndex2++;
                                        final Cell cell12 = row3.createCell(colIndex2);
                                        colIndex2++;
                                    }
                                }
                                CellRangeAddress region3 = new CellRangeAddress(startIndex2, rowIndex - 1, 2, 2);
                                if (rowIndex - 1 > startIndex2) {
                                    sheet.addMergedRegion(region3);
                                }
                            }
                        }
                        CellRangeAddress region2 = new CellRangeAddress(startIndex1, rowIndex - 1, 1, 1);
                        if (rowIndex - 1 > startIndex1) {
                            sheet.addMergedRegion(region2);
                        }
                    }
                }
                CellRangeAddress region = new CellRangeAddress(startIndex0, rowIndex - 1, 0, 0);
                if (rowIndex - 1 > startIndex0) {
                    sheet.addMergedRegion(region);
                }
            }

            sheet.addMergedRegion(new CellRangeAddress(2, 4, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 4, 6, 6));
            for (int i = 4; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell celli = row.getCell(j);
                    if (celli == null) {
                        celli = row.createCell(j);
                        celli.setCellStyle(setBorder2);
                    } else {
                        if (celli.getCellStyle() == null) {
                            celli.setCellStyle(setBorder2);
                        } else {
                            if (celli.getCellStyle().getFillForegroundColor() != IndexedColors.GREEN.getIndex()
                                    && celli.getCellStyle().getFillForegroundColor() != IndexedColors.RED.getIndex()) {
                                celli.setCellStyle(setBorder2);
                            }
                        }
                    }
                }
            }
            sheet.setColumnWidth(0, 15 * 256);
            sheet.setColumnWidth(1, 15 * 256);
            sheet.setColumnWidth(2, 15 * 256);
            sheet.setColumnWidth(3, 30 * 256);
            sheet.setColumnWidth(4, 12 * 256);
            sheet.setColumnWidth(5, 12 * 256);
            sheet.setColumnWidth(6, 20 * 256);
            // 导出Excel文件
            String filename = "能力数据" + String.valueOf(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format2 = sdf.format(new Date());
            String filePath = rootPath + "pcb\\" + format2 + "\\" + filename + ".xlsx";
            File folder = new File(rootPath + "pcb\\" + format2);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //导出模板
    @Override
    public Result outputParamTemplate(String version) throws IOException {
        List<PcbCapacityParamHistory> paramList = new ArrayList();
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version是空的", "param version is null", null);
        }
        final PcbCapacityParamVersion newestVersion = getNewestVersion(null, 2);
        String str_newestVersion = "";
        if (newestVersion != null && version.equals(newestVersion.getVersionYear() + "_" + newestVersion.getVersionNum())) {
            List<PcbCapacityParam> childrenById = getChildrenById(0, null, 1);
            for (int i = 0; i < childrenById.size(); i++) {
                paramList.add(new PcbCapacityParamHistory(childrenById.get(i)));
            }
        } else {
            paramList = getChildrenByIdHistory(0, version);
            if (paramList == null || paramList.size() == 0) {
                return ResultUtil.error(500, "没有该年份的模板", "", null);
            }
        }
        int startIndex;
        int startIndex1;
        int startIndex2;
        // 创建工作簿对象
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表对象
        Sheet sheet = workbook.createSheet("Sheet1");
        XSSFCellStyle setBorder = getStyle1(workbook);
        XSSFCellStyle setBorder2 = getStyle2(workbook);
        XSSFCellStyle setFont = getStyleFont(workbook);
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Row rowTR = sheet.createRow(0);
        Cell cellTR0 = rowTR.createCell(0);
        cellTR0.setCellValue("下载时间：");
        cellTR0.setCellStyle(setFont);
        Cell cellTR1 = rowTR.createCell(1);
        cellTR1.setCellValue(format.format(new Date()));
        Cell cellTR2 = rowTR.createCell(2);
        cellTR2.setCellValue("下载人员：");
        cellTR2.setCellStyle(setFont);
        Cell cellTR3 = rowTR.createCell(3);
        cellTR3.setCellValue(UserHeaderHolder.getDomainAccount());
        Cell cellTR4 = rowTR.createCell(4);
        cellTR4.setCellValue("版本：");
        cellTR4.setCellStyle(setFont);
        Cell cellTR5 = rowTR.createCell(5);
        cellTR5.setCellValue(StringUtils.isBlank(version) ? "" : version);

        Row rowT0 = sheet.createRow(1);
        Cell cell8 = rowT0.createCell(0);
        cell8.setCellValue("PCB能力项");
        cell8.setCellStyle(setBorder);
        Cell cell81 = rowT0.createCell(1);
        cell81.setCellStyle(setBorder);
        Cell cell82 = rowT0.createCell(2);
        cell82.setCellStyle(setBorder);
        Cell cell83 = rowT0.createCell(3);
        cell83.setCellStyle(setBorder);
        // 合并第1行的第1个单元格到第3个单元格
        CellRangeAddress region0 = new CellRangeAddress(1, 1, 0, 3);
        sheet.addMergedRegion(region0);
        Row rowT1 = sheet.createRow(2);
        Cell cell0 = rowT1.createCell(0);
        cell0.setCellValue("类型");
        cell0.setCellStyle(setBorder);
        Cell cell2 = rowT1.createCell(1);
        cell2.setCellValue("类别");
        cell2.setCellStyle(setBorder);
        Cell cell3 = rowT1.createCell(2);
        cell3.setCellStyle(setBorder);
        cell3.setCellValue("大类");
        Cell cell4 = rowT1.createCell(3);
        cell4.setCellStyle(setBorder);
        cell4.setCellValue("小类");
        Cell cell5 = rowT1.createCell(4);
        cell5.setCellStyle(setBorder);
        cell5.setCellValue("厂家能力");
        Cell cell55 = rowT1.createCell(5);
        cell55.setCellStyle(setBorder);
        cell55.setCellValue("厂家");
        Cell cell66 = rowT1.createCell(6);
        cell66.setCellStyle(setBorder);
        cell66.setCellValue("说明");
        Cell cell77 = rowT1.createCell(7);
        cell77.setCellStyle(setBorder);
        cell77.setCellValue("规则");

        int columIndex = 0;
        Row rowT2 = sheet.createRow(3);
        final Cell cell14 = rowT2.createCell(1);
        cell14.setCellStyle(setBorder);
        final Cell cell15 = rowT2.createCell(2);
        cell15.setCellStyle(setBorder);
        final Cell cell16 = rowT2.createCell(3);
        cell16.setCellStyle(setBorder);
        final Cell cell17 = rowT2.createCell(4);
        cell17.setCellStyle(setBorder);
        final Cell cell18 = rowT2.createCell(5);
        cell18.setCellStyle(setBorder);
        final Cell cell19 = rowT2.createCell(6);
        cell19.setCellStyle(setBorder);
        final Cell cell20 = rowT2.createCell(7);
        cell20.setCellStyle(setBorder);
        Row rowT3 = sheet.createRow(4);
        final Cell cell143 = rowT3.createCell(1);
        cell143.setCellStyle(setBorder);
        final Cell cell153 = rowT3.createCell(2);
        cell153.setCellStyle(setBorder);
        final Cell cell163 = rowT3.createCell(3);
        cell163.setCellStyle(setBorder);
        final Cell cell173 = rowT3.createCell(4);
        cell173.setCellValue("量产能力");
        cell173.setCellStyle(setBorder);
        final Cell cell183 = rowT3.createCell(5);
        cell183.setCellValue("小批量能力");
        cell183.setCellStyle(setBorder);
        final Cell cell193 = rowT3.createCell(6);
        cell193.setCellStyle(setBorder);
        final Cell cell194 = rowT3.createCell(7);
        cell194.setCellStyle(setBorder);
        int rowIndex = 5;
        for (int i = 0; i < paramList.size(); i++) {
            startIndex = rowIndex;

            Row row = sheet.createRow(rowIndex);
            rowIndex++;

            Cell cell = row.createCell(0);
            cell.setCellValue(paramList.get(i).getPcbCapacityParamName());

            List<PcbCapacityParamHistory> categorys = paramList.get(i).getChildren();
            if (categorys != null) {
                for (int j = 0; j < categorys.size(); j++) {
                    Row row2;
                    if (j == 0) {
                        startIndex1 = startIndex;
                        row2 = row;
                    } else {
                        startIndex1 = rowIndex;
                        row2 = sheet.createRow(rowIndex);
                        rowIndex++;
                    }

                    Cell cell1 = row2.createCell(1);
                    cell1.setCellValue(categorys.get(j).getPcbCapacityParamName());
                    cell1.setCellStyle(setBorder2);
                    List<PcbCapacityParamHistory> bigType = categorys.get(j).getChildren();
                    if (bigType != null) {
                        for (int k = 0; k < bigType.size(); k++) {

                            Row row3;
                            if (k == 0) {
                                startIndex2 = startIndex1;
                                row3 = row2;
                            } else {
                                startIndex2 = rowIndex;
                                row3 = sheet.createRow(rowIndex);
                                rowIndex++;
                            }
                            row3.createCell(2).setCellValue(bigType.get(k).getPcbCapacityParamName());
                            List<PcbCapacityParamHistory> smallType = bigType.get(k).getChildren();
                            if (smallType != null) {
                                for (int m = 0; m < smallType.size(); m++) {
                                    Row row4;
                                    if (m == 0) {
                                        row4 = row3;
                                    } else {
                                        row4 = sheet.createRow(rowIndex);
                                        rowIndex++;
                                    }
                                    row4.createCell(3).setCellValue(smallType.get(m).getPcbCapacityParamName());
                                    row4.createCell(4).setCellValue("");
                                    row4.createCell(5).setCellValue("");
                                    row4.createCell(6).setCellValue(getStringParamType(smallType.get(m).getParamType()));//+","+(smallType.get(m).getRemark()==null?"":smallType.get(m).getRemark())
                                    row4.createCell(7).setCellValue(getStringRuleType(bigType.get(k).getRuleType()));//+","+(smallType.get(m).getRemark()==null?"":smallType.get(m).getRemark())
                                }
                            }
                            CellRangeAddress region3 = new CellRangeAddress(startIndex2, rowIndex - 1, 2, 2);
                            if (rowIndex - 1 > startIndex2) {
                                sheet.addMergedRegion(region3);
                            }
                        }
                    }
                    CellRangeAddress region1 = new CellRangeAddress(startIndex1, rowIndex - 1, 1, 1);
                    if (rowIndex - 1 > startIndex1) {
                        sheet.addMergedRegion(region1);
                    }
                }

            }
            CellRangeAddress region1 = new CellRangeAddress(startIndex, rowIndex - 1, 0, 0);
            if (rowIndex - 1 > startIndex) {
                sheet.addMergedRegion(region1);
            }
        }

        int columnCount = 8;
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 1, 1));
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 2, 2));
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 3, 3));
        sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 5));
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 6, 6));
        sheet.addMergedRegion(new CellRangeAddress(2, 4, 7, 7));
        for (int i = 4; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                row = sheet.createRow(i);
            }
            for (int j = 0; j < columnCount; j++) {
                Cell celli = row.getCell(j);
                if (celli == null) {
                    celli = row.createCell(j);
                }
                celli.setCellStyle(setBorder2);
            }
        }
        sheet.setColumnWidth(0, 15 * 256);
        sheet.setColumnWidth(1, 15 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 15 * 256);
        sheet.setColumnWidth(4, 12 * 256);
        sheet.setColumnWidth(5, 12 * 256);
        sheet.setColumnWidth(6, 20 * 256);
        sheet.setColumnWidth(7, 12 * 256);
        // 导出Excel文件
        String filename = "pcb模板" + String.valueOf(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format2 = sdf.format(new Date());
        File folder = new File(rootPath + "pcb\\" + format2);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = rootPath + "pcb\\" + format2 + "\\" + filename + ".xlsx";
        FileOutputStream outputStream = new FileOutputStream(filePath);
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
        return ResultUtil.success(filePath);
    }


    /*
    ruleType 规则类型，是大于还是小于等
    valueType 数据类型，是整数，浮点数，公差
    返回值：1 满足，0 不满足 ,没有就返回null
     */
    public Integer checkIsSatisfied(Integer ruleType, Integer valueType, String valueH3C, String valueFactory) {
        if (ruleType == null) {
            return null;
        }
        if (StringUtils.isBlank(valueFactory) || StringUtils.isBlank(valueH3C) || valueFactory.equals("/") || valueFactory.equals("*")) {
            return null;
        }
        //浮点数
        if (valueType.equals(DB2Config.valueTypeFloatNum) || valueType.equals(DB2Config.valueTypeText)) {
            //如果不是数字
            if (!StringUtils.isNumeric(valueFactory) || !StringUtils.isNumeric(valueH3C)) {
                return 0;
            }

            if (ruleType.equals(DB2Config.ruleTypeGreaterAndEqual)) {
                return Double.parseDouble(valueFactory) >= Double.parseDouble(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeLesserAndEqual)) {
                return Double.parseDouble(valueFactory) <= Double.parseDouble(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeGreater)) {
                return Double.parseDouble(valueFactory) > Double.parseDouble(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeLesser)) {
                return Double.parseDouble(valueFactory) < Double.parseDouble(valueH3C) ? 1 : 0;
            }
        }
        //整数
        if (valueType.equals(DB2Config.valueTypeIntergerNum) || valueType.equals(DB2Config.valueTypeText)) {
            //如果不是数字
            if (!StringUtils.isNumeric(valueFactory) || !StringUtils.isNumeric(valueH3C)) {
                return 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeGreaterAndEqual)) {
                return Integer.parseInt(valueFactory) >= Integer.parseInt(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeLesserAndEqual)) {
                return Integer.parseInt(valueFactory) <= Integer.parseInt(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeGreater)) {
                return Integer.parseInt(valueFactory) > Integer.parseInt(valueH3C) ? 1 : 0;
            }
            if (ruleType.equals(DB2Config.ruleTypeLesser)) {
                return Integer.parseInt(valueFactory) < Integer.parseInt(valueH3C) ? 1 : 0;
            }
        }
        //范围比较
        if (valueType.equals(DB2Config.valueTypeText) && ruleType.equals(DB2Config.ruleTypeRange))//
        {
            if (valueH3C.contains("~") && valueFactory.contains("~")) {
                String s = valueH3C.split("~")[0];
                //如果不是数字
                if (!StringUtils.isNumeric(valueH3C.split("~")[0]) || !StringUtils.isNumeric(valueH3C.split("~")[1])) {
                    return null;
                }
                if (!StringUtils.isNumeric(valueFactory.split("~")[0]) || !StringUtils.isNumeric(valueFactory.split("~")[1])) {
                    return 0;
                }
                double rangH3C1 = Double.parseDouble(valueH3C.split("~")[0]);
                double rangH3C2 = Double.parseDouble(valueH3C.split("~")[1]);
                double rangFac1 = Double.parseDouble(valueFactory.split("~")[0]);
                double rangFac2 = Double.parseDouble(valueFactory.split("~")[1]);

                if (rangFac1 <= rangH3C1 && rangH3C2 <= rangFac2) {
                    return 1;
                }
            }
        }
        //浮点数*浮点数
        if (valueType.equals(DB2Config.valueTypeFloatMuti)) {
            if (valueH3C.contains("*") && valueFactory.contains("*")) {
                String s = valueH3C.split("\\*")[0];
                //如果不是数字
                if (!StringUtils.isNumeric(valueH3C.split("~")[0]) || !StringUtils.isNumeric(valueH3C.split("~")[1])) {
                    return null;
                }
                if (!StringUtils.isNumeric(valueFactory.split("~")[0]) || !StringUtils.isNumeric(valueFactory.split("~")[1])) {
                    return 0;
                }
                double rangH3C1 = Double.parseDouble(valueH3C.split("\\*")[0]);
                double rangH3C2 = Double.parseDouble(valueH3C.split("\\*")[1]);
                double rangFac1 = Double.parseDouble(valueFactory.split("\\*")[0]);
                double rangFac2 = Double.parseDouble(valueFactory.split("\\*")[1]);

                if (rangH3C1 <= rangFac1 && rangH3C2 <= rangFac2) {
                    return 1;
                }
            }
        }
        //浮点数/浮点数
        if (valueType.equals(DB2Config.valueTypeFloatDiv)) {
            if (valueH3C.contains("/") && valueFactory.contains("/")) {
                String s = valueH3C.split("/")[0];
                //如果不是数字
                if (!StringUtils.isNumeric(valueH3C.split("~")[0]) || !StringUtils.isNumeric(valueH3C.split("~")[1])) {
                    return null;
                }
                if (!StringUtils.isNumeric(valueFactory.split("~")[0]) || !StringUtils.isNumeric(valueFactory.split("~")[1])) {
                    return 0;
                }
                double rangH3C1 = Double.parseDouble(valueH3C.split("/")[0]);
                double rangH3C2 = Double.parseDouble(valueH3C.split("/")[1]);
                double rangFac1 = Double.parseDouble(valueFactory.split("/")[0]);
                double rangFac2 = Double.parseDouble(valueFactory.split("/")[1]);

                if (rangH3C1 <= rangFac1 && rangH3C2 <= rangFac2) {
                    return 1;
                }
            }
        }
        //浮点数~浮点数
        if (valueType.equals(DB2Config.valueTypeFloatWave)) {
            if (valueH3C.contains("~") && valueFactory.contains("~")) {
                String s = valueH3C.split("~")[0];
                //如果不是数字
                if (!StringUtils.isNumeric(valueH3C.split("~")[0]) || !StringUtils.isNumeric(valueH3C.split("~")[1])) {
                    return null;
                }
                if (!StringUtils.isNumeric(valueFactory.split("~")[0]) || !StringUtils.isNumeric(valueFactory.split("~")[1])) {
                    return 0;
                }
                double rangH3C1 = Double.parseDouble(valueH3C.split("~")[0]);
                double rangH3C2 = Double.parseDouble(valueH3C.split("~")[1]);
                double rangFac1 = Double.parseDouble(valueFactory.split("~")[0]);
                double rangFac2 = Double.parseDouble(valueFactory.split("~")[1]);

                if (rangH3C1 <= rangFac1 && rangH3C2 >= rangFac2) {
                    return 1;
                }
            }
        }
        return 0;
    }


    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result importParamTemplate(MultipartFile file, String typeT) throws IOException {

        if (file == null) {
            return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
        }
        String userId = UserHeaderHolder.getUserId();
        InputStream fileInputStream = file.getInputStream();
        String str_warning = "";
        try {
            File f = FileConverterUtils.getTempFileFromInputStream(fileInputStream);
            Workbook workbook = WorkbookFactory.create(f);
            Sheet sheet = workbook.getSheetAt(0);
            String type = "";
            String category = "";
            String bigType = "";
            String smallType = "";
            Integer typeId = null;
            Integer categoryId = null;
            Integer bigTypeId = null;
            String[] headers = new String[]{"类型", "类别", "大类", "小类"};
            Row rowH = sheet.getRow(2);
            for (int i = 0; i < 4; i++) {
                Cell cell = rowH.getCell(i);
                if (cell == null) {
                    return ResultUtil.error(500, "导入文件格式不匹配", "template is error", null);
                } else {
                    cell.setCellType(CellType.STRING);
                    if (!cell.getStringCellValue().trim().equals(headers[i])) {
                        return ResultUtil.error(500, "导入文件格式不匹配", "template is error", null);
                    }
                }
            }
            int sort0 = 0;
            int sort1 = 0;
            int sort2 = 0;
            int sort3 = 0;
            for (int i = 5; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Cell cell0 = row.getCell(0);
                if (cell0 == null) {
                    str_warning += "第" + (i + 1) + "行1列单元格内容为空;";
                    continue;
                }
                cell0.setCellType(CellType.STRING);
                String stringCellValue0 = cell0.getStringCellValue();
                boolean flagChange0 = false;
                boolean flagChange1 = false;
                boolean flagChange2 = false;
                //类型
                if (!StringUtils.isBlank(stringCellValue0)) {
                    sort0 += 100000;
                    flagChange0 = true;
                    type = stringCellValue0;
                    if (StringUtils.isBlank(type)) {
                        return ResultUtil.error(500, "类型为空", " type is null", null);
                    }
                    List<PcbCapacityParam> types = pcbCapacityParamDao.getAllByLimit(null, type, null, null, null, null, null, 0, null, null, null, null, null);
                    if (types == null || types.size() == 0) {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(type);
                        pcbCapacityParam.setParentId(0);
                        pcbCapacityParam.setLevel(0);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort0);
                        pcbCapacityParam.setStatus(1);
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        typeId = pcbCapacityParam.getPcbCapacityParamId();
                    } else {
                        typeId = types.get(0).getPcbCapacityParamId();
                        PcbCapacityParam pcbCapacityParam = types.get(0);
                        pcbCapacityParam.setSort(sort0);
                        pcbCapacityParamDao.update(pcbCapacityParam);
                    }
                }

                //类别
                Cell cell1 = row.getCell(1);
                if (cell1 == null) {
                    str_warning += "第" + (i + 1) + "行3列单元格内容为空;";
                    continue;
                }
                cell1.setCellType(CellType.STRING);
                String stringCellValue1 = cell1.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue1)) {
                    category = stringCellValue1;
                    flagChange1 = true;
                    if (flagChange0) {
                        sort1 = sort0 + 10000;
                    } else {
                        sort1 += 10000;
                    }
                    List<PcbCapacityParam> categorys = pcbCapacityParamDao.getAllByLimit(null, category, null, null, null, null, null, 1, null, null, null, null, null);
                    if (categorys == null || categorys.size() == 0) {
//                    return  ResultUtil.error(500,category+"类型不存在",category+" not exist",null);
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(category);
                        pcbCapacityParam.setParentId(typeId);
                        pcbCapacityParam.setIndexLink(typeId + "-");
                        pcbCapacityParam.setLevel(1);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort1);
                        pcbCapacityParam.setStatus(1);
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        categoryId = pcbCapacityParam.getPcbCapacityParamId();
                    } else {
                        categoryId = categorys.get(0).getPcbCapacityParamId();
                        PcbCapacityParam pcbCapacityParam = categorys.get(0);
                        pcbCapacityParam.setSort(sort1);
                        pcbCapacityParamDao.update(pcbCapacityParam);
                    }
                }

                //大类
                Cell cell2 = row.getCell(2);
                if (cell2 == null) {
                    str_warning += "第" + (i + 1) + "行3列单元格内容为空;";
                    continue;
                }
                cell2.setCellType(CellType.STRING);
                String stringCellValue2 = cell2.getStringCellValue();
                Cell cell5 = row.getCell(7);
                if (cell5 != null) {
                    cell5.setCellType(CellType.STRING);
                }
                String str_ruleType = cell5 == null ? "" : cell5.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue2)) {
                    if (flagChange1) {
                        sort2 = sort1 + 100;
                    } else {
                        sort2 += 100;
                    }
                    flagChange2 = true;
                    bigType = stringCellValue2;
                    List<PcbCapacityParam> bigTypes = pcbCapacityParamDao.getAllByLimit(null, bigType, null, null, null, null, null, 2, null, null, null, null, null);
                    if (bigTypes == null || bigTypes.size() == 0) {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(bigType);
                        pcbCapacityParam.setParentId(categoryId);
                        pcbCapacityParam.setIndexLink(typeId + "-" + categoryId + "-");
                        pcbCapacityParam.setLevel(2);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort2);
                        pcbCapacityParam.setStatus(1);
                        pcbCapacityParam.setRuleType(checkRuleType(str_ruleType));
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        bigTypeId = pcbCapacityParam.getPcbCapacityParamId();
                    } else {
                        bigTypeId = bigTypes.get(0).getPcbCapacityParamId();
                        PcbCapacityParam pcbCapacityParam = bigTypes.get(0);
                        pcbCapacityParam.setSort(sort2);
                        pcbCapacityParam.setRuleType(checkRuleType(str_ruleType));
                        pcbCapacityParamDao.update(pcbCapacityParam);
                    }
                }

                //小类
                Cell cell3 = row.getCell(3);
                if (cell3 == null) {
                    str_warning += "第" + (i + 1) + "行4列单元格内容为空;";
                    continue;
                }
                cell3.setCellType(CellType.STRING);
                String stringCellValue3 = cell3.getStringCellValue();
                Cell cell4 = row.getCell(6);
                if (cell4 == null) {
                    str_warning += "第" + (i + 1) + "行7列单元格内容为空;";
                    continue;
                }
                cell4.setCellType(CellType.STRING);
                String str_paramType = cell4.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue3)) {
                    smallType = stringCellValue3;
                    if (flagChange2) {
                        sort3 = sort2 + 10;
                    } else {
                        sort3 += 10;
                    }
                    String dataType = str_paramType;
                    if (StringUtils.isBlank(str_paramType)) {
                        str_warning += "第" + (i + 1) + "行7列单元格内容为空;";
                        continue;
                    }
                    Integer paramType = checkType(dataType);
                    String str_options = "";
                    if (paramType == 2 && (str_paramType.contains("：") || str_paramType.contains(":"))) {
                        str_paramType = str_paramType.replace("：", ":");
                        str_options = str_paramType.substring(str_paramType.lastIndexOf(":") + 1).replace('/', ',').replace('，', ',');
                    }
                    List<PcbCapacityParam> smallTypes = pcbCapacityParamDao.getAllByLimit(bigTypeId, smallType, null, null, null, null, null, 3, null, null, null, null, null);
                    if (smallTypes == null || smallTypes.size() == 0) {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setParentId(bigTypeId);
                        pcbCapacityParam.setPcbCapacityParamName(smallType);
                        String key = String.valueOf(System.currentTimeMillis());
                        pcbCapacityParam.setIndexLink(typeId + "-" + categoryId + "-" + bigTypeId + "-");
                        pcbCapacityParam.setPcbCapacityParamKey("input_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey2("input2_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey3("input3_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey4("input4_" + key);
                        pcbCapacityParam.setLevel(3);
                        pcbCapacityParam.setIsRequired(1);//StringUtils.isBlank(str_isRequired) ? 1 : Integer.parseInt(str_isRequired)
                        pcbCapacityParam.setParamType(paramType);
                        pcbCapacityParam.setParamOptions(str_options);
                        pcbCapacityParam.setRuleType(null);
                        pcbCapacityParam.setUnit("");
                        pcbCapacityParam.setTip("");
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setRemark(null);
                        pcbCapacityParam.setSort(sort3);//StringUtils.isBlank(str_sort) ? 100 : Integer.parseInt(str_sort)
                        pcbCapacityParam.setStatus(1);//StringUtils.isBlank(str_status) ? null : Integer.parseInt(str_status)
                        pcbCapacityParamDao.insert(pcbCapacityParam);
                    } else {
                        PcbCapacityParam pcbCapacityParam = smallTypes.get(0);
                        pcbCapacityParam.setIndexLink(typeId + "-" + categoryId + "-" + bigTypeId + "-");
                        pcbCapacityParam.setParamType(paramType);
                        pcbCapacityParam.setParamOptions(str_options);
                        pcbCapacityParam.setRuleType(null);
                        pcbCapacityParam.setUpdateUser(userId);
                        pcbCapacityParam.setUpdateTime(new Date());
                        pcbCapacityParam.setRemark(null);
                        pcbCapacityParam.setSort(sort3);
                        pcbCapacityParam.setStatus(1);
                        pcbCapacityParamDao.update(pcbCapacityParam);
                    }
                } else {
                    str_warning += "第" + (i + 1) + "行4列单元格内容为空;";
                    continue;
                }
            }
            if (!StringUtils.isBlank(str_warning) && typeT.equals("0")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error(500, str_warning, str_warning, null);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        } finally {
            fileInputStream.close();
        }

    }

    //覆盖导入
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result importParamTemplate2(MultipartFile file, String typeT) throws IOException {

        if (file == null) {
            return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
        }
        String str_warning = "";
        String userId = UserHeaderHolder.getUserId();
        InputStream fileInputStream = file.getInputStream();
        try {
            File f = FileConverterUtils.getTempFileFromInputStream(fileInputStream);
            Workbook workbook = WorkbookFactory.create(f);
            Sheet sheet = workbook.getSheetAt(0);
            String type = "";
            String category = "";
            String bigType = "";
            String smallType = "";
            Integer typeId = null;
            Integer categoryId = null;
            Integer bigTypeId = null;
            String[] headers = new String[]{"类型", "类别", "大类", "小类"};
            Row rowH = sheet.getRow(2);
            for (int i = 0; i < 4; i++) {
                Cell cell = rowH.getCell(i);
                if (cell == null) {
                    return ResultUtil.error(500, "导入文件格式不匹配", "template is error", null);
                }
                if (!cell.getStringCellValue().trim().equals(headers[i])) {
                    return ResultUtil.error(500, "导入文件格式不匹配", "template is error", null);
                }
            }
            int sort0 = 0;
            int sort1 = 0;
            int sort2 = 0;
            int sort3 = 0;
            pcbCapacityParamDao.deleteAll();
            final int lastRowNum = sheet.getLastRowNum();
            for (int i = 5; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Cell cell0 = row.getCell(0);
                if (cell0 == null) {
                    str_warning += "第" + (i + 1) + "行1列单元格内容为空;";
                    continue;
                }
                cell0.setCellType(CellType.STRING);
                String stringCellValue0 = cell0.getStringCellValue();
                boolean flagChange0 = false;
                boolean flagChange1 = false;
                boolean flagChange2 = false;
                //类型
                if (!StringUtils.isBlank(stringCellValue0)) {
                    sort0 += 100000;
                    flagChange0 = true;
                    type = stringCellValue0;
                    if (StringUtils.isBlank(type)) {
                        return ResultUtil.error(500, "类型为空", " type is null", null);
                    }
                    {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(type);
                        pcbCapacityParam.setParentId(0);
                        pcbCapacityParam.setLevel(0);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort0);
                        pcbCapacityParam.setStatus(1);
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        typeId = pcbCapacityParam.getPcbCapacityParamId();
                    }

                }

                //类别
                Cell cell1 = row.getCell(1);
                if (cell1 == null) {
                    str_warning += "第" + (i + 1) + "行2列单元格内容为空;";
                    continue;
                }
                cell1.setCellType(CellType.STRING);
                String stringCellValue1 = cell1.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue1)) {
                    category = stringCellValue1;
                    flagChange1 = true;
                    if (flagChange0) {
                        sort1 = sort0 + 10000;
                    } else {
                        sort1 += 10000;
                    }
                    {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(category);
                        pcbCapacityParam.setParentId(typeId);
                        pcbCapacityParam.setIndexLink(typeId + "-");
                        pcbCapacityParam.setLevel(1);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort1);
                        pcbCapacityParam.setStatus(1);
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        categoryId = pcbCapacityParam.getPcbCapacityParamId();
                    }

                }

                //大类
                Cell cell2 = row.getCell(2);
                if (cell2 == null) {
                    str_warning += "第" + (i + 1) + "行3列单元格内容为空;";
                    continue;
                }
                cell2.setCellType(CellType.STRING);
                String stringCellValue2 = cell2.getStringCellValue();
                Cell cell5 = row.getCell(7);
                if (cell5 != null) {
                    cell5.setCellType(CellType.STRING);
                }
                String str_ruleType = cell5 == null ? "" : cell5.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue2)) {
                    if (flagChange1) {
                        sort2 = sort1 + 100;
                    } else {
                        sort2 += 100;
                    }
                    flagChange2 = true;
                    bigType = stringCellValue2;
                    {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setPcbCapacityParamName(bigType);
                        pcbCapacityParam.setParentId(categoryId);
                        pcbCapacityParam.setIndexLink(typeId + "-" + categoryId + "-");
                        pcbCapacityParam.setLevel(2);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setSort(sort2);
                        pcbCapacityParam.setStatus(1);
                        pcbCapacityParam.setRuleType(checkRuleType(str_ruleType));
                        Integer count = pcbCapacityParamDao.insert(pcbCapacityParam);
                        bigTypeId = pcbCapacityParam.getPcbCapacityParamId();
                    }

                }

                //小类
                Cell cell3 = row.getCell(3);
                if (cell3 == null) {
                    str_warning += "第" + (i + 1) + "行4列单元格内容为空;";
                    continue;
                }
                cell3.setCellType(CellType.STRING);
                String stringCellValue3 = cell3.getStringCellValue();

                Cell cell4 = row.getCell(6);
                if (cell4 == null) {
                    str_warning += "第" + (i + 1) + "行7列单元格内容为空;";
                    continue;
                }
                cell4.setCellType(CellType.STRING);
                String str_paramType = cell4.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue3)) {
                    smallType = stringCellValue3;
                    if (flagChange2) {
                        sort3 = sort2 + 10;
                    } else {
                        sort3 += 10;
                    }
                    String dataType = str_paramType;
                    if (StringUtils.isBlank(str_paramType)) {
                        str_warning += "第" + (i + 1) + "行7列单元格内容为空;";
                        continue;
                    }
                    Integer paramType = checkType(dataType);
                    String str_options = "";
                    if (paramType == 2 && (str_paramType.contains("：") || str_paramType.contains(":"))) {
                        str_paramType = str_paramType.replace("：", ":");
                        str_options = str_paramType.substring(str_paramType.lastIndexOf(":") + 1).replace('/', ',').replace('，', ',');
                    }
                    {
                        PcbCapacityParam pcbCapacityParam = new PcbCapacityParam();
                        pcbCapacityParam.setParentId(bigTypeId);
                        pcbCapacityParam.setPcbCapacityParamName(smallType);
                        String key = String.valueOf(System.currentTimeMillis());
                        Random random = new Random();
                        // 生成一个1000以内的随机整数（包括0）
                        int randomNumber = random.nextInt(1000);
                        // 将整数转换为字符串
                        String randomNumberString = Integer.toString(randomNumber);
                        key += randomNumberString;
                        pcbCapacityParam.setIndexLink(typeId + "-" + categoryId + "-" + bigTypeId + "-");
                        pcbCapacityParam.setPcbCapacityParamKey("input_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey2("input2_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey3("input3_" + key);
                        pcbCapacityParam.setPcbCapacityParamKey4("input4_" + key);
                        pcbCapacityParam.setLevel(3);
                        pcbCapacityParam.setIsRequired(1);//StringUtils.isBlank(str_isRequired) ? 1 : Integer.parseInt(str_isRequired)
                        pcbCapacityParam.setParamType(paramType);
                        pcbCapacityParam.setParamOptions(str_options);
                        pcbCapacityParam.setRuleType(null);
                        pcbCapacityParam.setUnit("");
                        pcbCapacityParam.setTip("");
                        pcbCapacityParam.setCreateUser(userId);
                        pcbCapacityParam.setCreateTime(new Date());
                        pcbCapacityParam.setRemark(null);
                        pcbCapacityParam.setSort(sort3);//StringUtils.isBlank(str_sort) ? 100 : Integer.parseInt(str_sort)
                        pcbCapacityParam.setStatus(1);//StringUtils.isBlank(str_status) ? null : Integer.parseInt(str_status)
                        pcbCapacityParamDao.insert(pcbCapacityParam);
                    }

                }
            }
            if (!StringUtils.isBlank(str_warning) && typeT.equals("0")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error(500, str_warning, str_warning, null);
            }
            pcbCapacityDataDao.deleteAll();
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        } finally {
            fileInputStream.close();
        }

    }

    @Override
    public Boolean checkHasSonParam(Integer paramId) {
        List<PcbCapacityParam> oldData = pcbCapacityParamDao.getAllByLimit(paramId, null, null, null, null, null, null, null, null, null, null, null, null);
        if (oldData != null && oldData.size() > 0) {
            return false;
        }
        return true;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result publishTemplate() {
        try {
            String userId = UserHeaderHolder.getUserId();
            int flowType = 3;
            List<PcbParentFactoryInfo> pcbParentFactoryInfoList = pcbParentFactoryInfoService.getAll(null, null, null, null, null, null, null, null, null, null, null, null, 1, null);
            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++) {
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        PcbApproveConfig oneByLimit = pcbApproveConfigDao.getOneByLimit(flowType, null, sonFactoryInfos.get(j).getPcbSonFactoryId());
                        if (oneByLimit == null) {
                            return ResultUtil.error(500, "请先配置" + "相关流程的审核人员", "Fail", null);
                        }
                        List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getTwoTypes(sonFactoryInfos.get(j).getPcbSonFactoryId());
                        if (byLimit.size() > 0) {
                            for (int k = 0; k < byLimit.size(); k++) {
                                if (byLimit.get(k).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                                    byLimit.get(k).setStatus(2);//将之前的都作废
                                    pcbCapacityDataApproveDao.update(byLimit.get(k));
                                } else {
                                    return ResultUtil.error(500, "厂家" + sonFactoryInfos.get(j).getSonFactoryName() + "有未处理完成的任务", "", null);
                                }
                            }
                        }
                    }
                }
            }

            PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getSystemStatus();
            if (pcbCapacityDataApprove != null) {
                Result result = checkHasNotApproved();
                //有未审核通过的
                if (result.getCode() == 500) {
                    return result;
                }
                final String strOld = toJSONString(pcbCapacityDataApprove);
                pcbCapacityDataApprove.setApproveStatus("已分发");
                pcbCapacityDataApprove.setApproveUserId(userId);
                pcbCapacityDataApprove.setUpdateUser(userId);
                pcbCapacityDataApprove.setUpdateTime(new Date());

                int count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
                if (count > 0) {
                    PcbCapacityDataApprove newData = pcbCapacityDataApproveDao.getById(pcbCapacityDataApprove.getId());
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 3, 1, new Date(), strOld, toJSONString(newData)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            } else {
                PcbCapacityDataApprove pcbCapacityDataApproveNew = new PcbCapacityDataApprove();
                pcbCapacityDataApproveNew.setFactoryId(0);
                pcbCapacityDataApproveNew.setApproveStatus("已分发");
                pcbCapacityDataApproveNew.setRemark("记录分发状态");
                pcbCapacityDataApproveNew.setApproveUserId(userId);
                pcbCapacityDataApproveNew.setCreateUser(userId);
                pcbCapacityDataApproveNew.setCreateTime(new Date());
                pcbCapacityDataApproveNew.setStatus(1);
                int count = pcbCapacityDataApproveDao.insert(pcbCapacityDataApproveNew);
                if (count > 0) {
                    operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 1, 1, new Date(), null, JSONObject.toJSONString(pcbCapacityDataApproveNew)));
                } else {
                    return ResultUtil.error(500, "操作失败", "Operate Fail", null);
                }
            }

            //自动创建流程
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String currentDate = sdf.format(new Date());
            PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
            int currentSeq = 0;
            String flowNum = "";
            if (byFlowNum != null) {
                currentSeq = byFlowNum.getSeq();
            }

            for (int i = 0; i < pcbParentFactoryInfoList.size(); i++) {
                List<PcbSonFactoryInfo> sonFactoryInfos = pcbParentFactoryInfoList.get(i).getSonFactoryInfos();
                if (sonFactoryInfos != null) {
                    for (int j = 0; j < sonFactoryInfos.size(); j++) {
                        currentSeq++;


                        PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, sonFactoryInfos.get(j).getPcbSonFactoryId());

                        //添加审批记录
                        flowNum = currentDate + String.format("%05d", currentSeq);
                        PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
                        pcbCapacityDataApprove1.setFlowNum(flowNum);
                        pcbCapacityDataApprove1.setSeq(currentSeq);
                        pcbCapacityDataApprove1.setFlowType(flowType);
                        pcbCapacityDataApprove1.setParentFactoryId(sonFactoryInfos.get(j).getParentId());
                        pcbCapacityDataApprove1.setFactoryId(sonFactoryInfos.get(j).getPcbSonFactoryId());
                        pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_FactoryHandle);
                        pcbCapacityDataApprove1.setCreateTime(new Date());
                        pcbCapacityDataApprove1.setCreateUser(userId);
                        pcbCapacityDataApprove1.setApproveUserId(approveConfig.getOperator().toString());
                        pcbCapacityDataApprove1.setStatus(1);
                        pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
                        //添加审批详情-创建流程
                        PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
                        pcbCapacityApproveDetail.setFlowType(flowType);
                        pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
                        pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                        pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
                        pcbCapacityApproveDetail.setDepartmentId(null);
                        pcbCapacityApproveDetail.setSonFactoryId(sonFactoryInfos.get(j).getPcbSonFactoryId());
                        pcbCapacityApproveDetail.setFileIds(null);
                        pcbCapacityApproveDetail.setRemark(null);
                        pcbCapacityApproveDetail.setCreateTime(new Date());
                        pcbCapacityApproveDetail.setCreateUser(userId);
                        pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator());
                        pcbCapacityApproveDetail.setStatus(1);
                        pcbCapacityApproveDetail.setSort(100);
                        pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
                        //添加审批过程记录
                        PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
                        pcbApproveProcess.setApproveType(flowType);
                        pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
                        pcbApproveProcess.setOldStatus("");
                        pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
                        pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                        pcbApproveProcess.setCreateTime(new Date());
                        pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
                        pcbApproveProcess.setApplyToId(null);
                        pcbApproveProcessDao.insert(pcbApproveProcess);
                        //添加审批详情-厂家处理
                        PcbCapacityApproveDetail pcbCapacityApproveDetail2 = new PcbCapacityApproveDetail();
                        pcbCapacityApproveDetail2.setFlowType(flowType);
                        pcbCapacityApproveDetail2.setDataId(pcbCapacityDataApprove1.getId());
                        pcbCapacityApproveDetail2.setApproveNode(DB2Config.CapacityDataStatus_FactoryHandle);
                        pcbCapacityApproveDetail2.setApplyUserId(Integer.parseInt(userId));
                        pcbCapacityApproveDetail2.setSonFactoryId(sonFactoryInfos.get(j).getPcbSonFactoryId());
                        pcbCapacityApproveDetail2.setCreateTime(new Date());
                        //bug修复，厂家处理没有审核人，2025/1/2，author:zyqin
                        pcbCapacityApproveDetail2.setApproveUserId(approveConfig.getOperator());
                        pcbCapacityApproveDetail2.setCreateUser(userId);
                        pcbCapacityApproveDetail2.setNextNodeUserId(approveConfig.getOperator2());
                        pcbCapacityApproveDetail2.setStatus(1);
                        pcbCapacityApproveDetail2.setSort(100);
                        pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail2);
                        //添加审批过程记录
                        PcbApproveProcess pcbApproveProcess2 = new PcbApproveProcess();
                        pcbApproveProcess2.setApproveType(flowType);
                        pcbApproveProcess2.setDataId(pcbCapacityDataApprove1.getId());
                        pcbApproveProcess2.setOldStatus(DB2Config.CapacityDataStatus_CreateFlow);
                        pcbApproveProcess2.setNewStatus(DB2Config.CapacityDataStatus_FactoryHandle);
                        pcbApproveProcess2.setApproveNode(DB2Config.CapacityDataStatus_FactoryHandle);
                        pcbApproveProcess2.setCreateTime(new Date());
                        pcbApproveProcess2.setApplyToId(approveConfig.getOperator());
                        pcbApproveProcessDao.insert(pcbApproveProcess2);
                    }
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }


    public Integer checkType(String cellValue) {
        cellValue = cellValue.trim();
        if (cellValue.equals("普通文本") || cellValue.equals("文本框")) {
            return 1;
        }
        if (cellValue.contains("下拉选择")) {
            return 2;
        }
        if (cellValue.equals("文件上传")) {
            return 3;
        }
        if (cellValue.equals("浮点型*浮点型")) {
            return 4;
        }
        if (cellValue.equals("浮点型/浮点型")) {
            return 5;
        }
        if (cellValue.equals("公差")) {
            return 6;
        }
        if (cellValue.equals("浮点型~浮点型")) {
            return 8;
        }
        if (cellValue.equals("数值类型[整数]")) {
            return 10;
        }
        if (cellValue.equals("数值类型[小数]")) {
            return 11;
        }
        return null;
    }

    public String getStringParamType(Integer paramType) {
        if (paramType == null) {
            return "";
        }
        if (paramType == 1) {
            return "文本框";
        }
        if (paramType == 2) {
            return "下拉选择";
        }
        if (paramType == 3) {
            return "文件上传";
        }
        if (paramType == 4) {
            return "浮点型*浮点型";
        }
        if (paramType == 5) {
            return "浮点型/浮点型";
        }
        if (paramType == 6) {
            return "公差";
        }
        if (paramType == 8) {
            return "浮点型~浮点型";
        }
        if (paramType == 10) {
            return "数值类型[整数]";
        }
        if (paramType == 11) {
            return "数值类型[小数]";
        }
        return "";
    }

    public Integer checkRuleType(String cellValue) {
        if (cellValue == null || StringUtils.isBlank(cellValue)) {
            return null;
        }
        if (cellValue.equals("大于等于")) {
            return 1;
        }
        if (cellValue.contains("小于等于")) {
            return 2;
        }
        if (cellValue.equals("大于")) {
            return 3;
        }
        if (cellValue.equals("小于")) {
            return 4;
        }
        if (cellValue.equals("等于")) {
            return 5;
        }
        if (cellValue.equals("符合范围")) {
            return 6;
        }
        return null;
    }

    public String getStringRuleType(Integer ruleType) {
        if (ruleType == null) {
            return "";
        }
        if (ruleType == 1) {
            return "大于等于";
        }
        if (ruleType == 2) {
            return "小于等于";
        }
        if (ruleType == 3) {
            return "大于";
        }
        if (ruleType == 4) {
            return "小于";
        }
        if (ruleType == 5) {
            return "等于";
        }
        if (ruleType == 6) {
            return "范围";
        }
        return "";
    }

    public XSSFCellStyle getStyle2(Workbook workbook) {
        XSSFCellStyle setBorder2 = (XSSFCellStyle) workbook.createCellStyle();
        setBorder2.setBorderBottom(BorderStyle.THIN);
        setBorder2.setBorderLeft(BorderStyle.THIN);
        setBorder2.setBorderRight(BorderStyle.THIN);
        setBorder2.setBorderTop(BorderStyle.THIN);
        setBorder2.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder2.setAlignment(HorizontalAlignment.LEFT);
        return setBorder2;
    }

    public XSSFCellStyle getStyle1(Workbook workbook) {
        XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
        setBorder.setBorderBottom(BorderStyle.THIN);
        setBorder.setBorderLeft(BorderStyle.THIN);
        setBorder.setBorderRight(BorderStyle.THIN);
        setBorder.setBorderTop(BorderStyle.THIN);
        setBorder.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder.setAlignment(HorizontalAlignment.LEFT);
        //创建字体 加粗
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBold(true);
        font.setFontHeight(11);
        setBorder.setFont(font);
        return setBorder;
    }

    public XSSFCellStyle getStyleFont(Workbook workbook) {
        XSSFCellStyle setBorder = (XSSFCellStyle) workbook.createCellStyle();
        //创建字体 加粗
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBold(true);
        font.setFontHeight(11);
        setBorder.setFont(font);
        return setBorder;
    }

    public XSSFCellStyle getStyleColor(Workbook workbook, short colorIndex) {
        XSSFCellStyle styleRed = (XSSFCellStyle) workbook.createCellStyle();
        styleRed.setBorderBottom(BorderStyle.THIN);
        styleRed.setBorderLeft(BorderStyle.THIN);
        styleRed.setBorderRight(BorderStyle.THIN);
        styleRed.setBorderTop(BorderStyle.THIN);
        styleRed.setVerticalAlignment(VerticalAlignment.CENTER);
        styleRed.setAlignment(HorizontalAlignment.LEFT);
        styleRed.setFillForegroundColor(colorIndex);
        styleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return styleRed;
    }

    @Override
    public Result deleteHistoryTemplate(String version) {
        if (StringUtils.isBlank(version)) {
            return ResultUtil.error(500, "参数version为空", "param version is null", null);
        }
        try {
            if (version.indexOf("_") == -1) {
                return ResultUtil.error(500, "参数version错误", "param version is error", null);
            }
            String oldVersionYear = version.substring(0, version.indexOf("_"));
            String oldVersionNum = version.substring(version.indexOf("_") + 1);
            int count = pcbCapacityParamVersionDao.deleteByVersion(oldVersionYear, oldVersionNum);
            count = pcbCapacityParamHistoryDao.deleteByVersion(oldVersionYear + "_" + oldVersionNum);
            count = pcbCapacityDataHistory2Dao.deleteByVersion(oldVersionYear + "_" + oldVersionNum);
            return ResultUtil.success(null);
        } catch (Exception e) {
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public PcbCapacityParamVersion getNewestVersion(String versionYear, Integer versionType) {
        PcbCapacityParamVersion pcbCapacityParamVersion = null;

        if (StringUtils.isBlank(versionYear)) {
            pcbCapacityParamVersion = pcbCapacityParamVersionDao.getNewest(versionType);
        } else {
            pcbCapacityParamVersion = pcbCapacityParamVersionDao.getNewestByVersionYear(versionYear, versionType);
        }
        return pcbCapacityParamVersion;
    }

    @Override
    public PcbCapacityParamVersion getNewestVersionByTemplateStatus(String versionYear, Integer versionType) {
        PcbCapacityParamVersion pcbCapacityParamVersion = null;
        PcbCapacityDataApprove systemStatus = pcbCapacityDataApproveDao.getSystemStatus();
        if (systemStatus.getApproveStatus().equals("已分发") || versionType == 2) {
            if (StringUtils.isBlank(versionYear)) {
                pcbCapacityParamVersion = pcbCapacityParamVersionDao.getNewest(versionType);
            } else {
                pcbCapacityParamVersion = pcbCapacityParamVersionDao.getNewestByVersionYear(versionYear, versionType);
            }
        } else {
            List<PcbCapacityParamVersion> versionListByTemplateStatus = getVersionListByTemplateStatus(versionYear, versionType);
            if (versionListByTemplateStatus.size() > 0) {
                pcbCapacityParamVersion = versionListByTemplateStatus.get(versionListByTemplateStatus.size() - 1);
            }
        }

        return pcbCapacityParamVersion;
    }

    @Override
    public Result saveTemplate(String versionYear, String versionNum) {
        String userId = UserHeaderHolder.getUserId();
        List<PcbCapacityParamVersion> versions = pcbCapacityParamVersionDao.getByLimit(null, versionYear, versionNum, 2);
        if (versions != null && versions.size() > 0) {
            return ResultUtil.error(500, "该版本的模板已存在", "", null);
        }
        try {
            PcbCapacityParamVersion newestByVersionYear = pcbCapacityParamVersionDao.getNewestByVersionYear(versionYear, 2);

            String oldVersionYear = null;
            String oldVersionNum = null;
            if (newestByVersionYear != null) {
                oldVersionYear = newestByVersionYear.getVersionYear();
                oldVersionNum = newestByVersionYear.getVersionNum();
            } else {
                newestByVersionYear = pcbCapacityParamVersionDao.getNewest(2);
                if (newestByVersionYear != null) {
                    oldVersionYear = newestByVersionYear.getVersionYear();
                    oldVersionNum = newestByVersionYear.getVersionNum();
                }
            }
            PcbCapacityParamVersion pcbCapacityParamVersion = new PcbCapacityParamVersion();
            pcbCapacityParamVersion.setVersionYear(versionYear);
            pcbCapacityParamVersion.setVersionNum(versionNum);
            pcbCapacityParamVersion.setCreateUser(userId);
            pcbCapacityParamVersion.setStatus(1);
            pcbCapacityParamVersion.setSort(100);
            pcbCapacityParamVersion.setCreateTime(new Date());
            pcbCapacityParamVersion.setVersionType(2);
            int count = pcbCapacityParamVersionDao.insert(pcbCapacityParamVersion);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力参数版本", 3, 1, new Date(), null, toJSONString(pcbCapacityParamVersion)));
            }
            //先保存能力参数
            if (!StringUtils.isBlank(oldVersionYear) && !StringUtils.isBlank(oldVersionNum)) {
                List<PcbCapacityParam> pcbCapacityParamListOld = pcbCapacityParamDao.getAllByLimit(null, null, null, null, null, null, null, null, null, null, null, null, null);
                List<PcbCapacityParamHistory> pcbCapacityParamHistoryList = new ArrayList<>();
                for (int i = 0; i < pcbCapacityParamListOld.size(); i++) {
                    PcbCapacityParamHistory pcbCapacityParamHistory = new PcbCapacityParamHistory(pcbCapacityParamListOld.get(i));
                    pcbCapacityParamHistory.setVersion(oldVersionYear + "_" + oldVersionNum);
                    pcbCapacityParamHistoryList.add(pcbCapacityParamHistory);
                }
                if (pcbCapacityParamHistoryList.size() > 0) {
                    count = pcbCapacityParamHistoryDao.insertBatch(pcbCapacityParamHistoryList);
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }
}


